Monday, October 25, 2010

SHARE - SpotCrime feed api integration

One of my client want to feed in the spotcrime map to one page for each his community site.
Each community have info about country, state/province, city, zipcode/postal code.
We can use this info for search it on google map.

First we need add this to your view

<%= javascript_include_tag('spotcrime/maps.js', 'spotcrime/main.js', 'spotcrime/spotcrime.js') %>


add this to view

<script type="text/javascript">
/* <[[CDATA] */
function initializeMap() {
SpotCrime.newsEmbed(
"map", //DOM that you want to add map
[<%= @lat %>, <%= @lng %>, 14], //latitude, longitude, zoom
[600,473], //width, height map
"<b><%= community.zipcode %><\/b>",
"<p style='font-size: smaller;'>Recent incident reports, MPD dispatches, and local crime news in the <%= community.zipcode %> zip code area.<\/p><br\/><br\/>");
}
/* ]> */
</script>



add this to your view

<div id="map"></div>


we need to get latitude and longitude for our community

add this to your controller

require 'open-uri'
require 'openssl'

url = "http://maps.googleapis.com/maps/api/geocode/xml?address=#{((community.address.to_s+' ')+(community.city.to_s+' ' if community.city)+(community.state.to_s+' ' if community.state)+(community.zipcode.to_s if community.zipcode)).gsub(' ', '+')}&sensor=true"
xml = open(url).read
hash = Hash.from_xml(xml)
if hash['GeocodeResponse'] and hash['GeocodeResponse']['result'] and hash['GeocodeResponse']['result']['geometry'] and hash['GeocodeResponse']['result']['geometry']['location']
@lat= hash['GeocodeResponse']['result']['geometry']['location']['lat'] if hash['GeocodeResponse']['result']['geometry']['location']['lat']
@lng= hash['GeocodeResponse']['result']['geometry']['location']['lng'] if hash['GeocodeResponse']['result']['geometry']['location']['lng']
end


for the js file you can ask me about it.

Wednesday, July 28, 2010

Web fonts using cufón

There are many ways use font on web apllication, one of them is use cufón.
cufón convert font(TrueType (TTF), OpenType (OTF), Printer Font Binary (PFB) and PostScript fonts) to JSON data.Then cufón will replace font text on your web apllication to font that you converted using cufón generator.

First we need some font that want to use. We can download font free on http://www.fontsquirrel.com/, http://www.fontyukle.com and many other websites.

Now we need to convert our font on http://cufon.shoqolate.com/generate.

If you have already converted it. Then download http://cufon.shoqolate.com/js/cufon-yui.js and save it on your javascript's folder.
Save the javascript that containing JSON data from our font on your javascript's folder too.

On your page

<script src="/javascripts/cufon-yui.js" type="text/javascript"></script>
<script src="/javascripts/fonts/Times New Roman.font.js" type="text/javascript"></script>


On your page

<div id='text_want_convert'>THIS TEXT WILL CONVERTED</div>


On your end of body tag

<script>
Cufon.replace(document.getElementById('text_want_convert') , { fontFamily: 'Times New Roman' })
</script>

Get Delivery Status from email sent using SendGrid API

Sometime when you send email to somebody, you want to know that the email sent or not right?

Sometime ago I use SendGrid for send email.

When using SendGrid for sending email, you can also add some custom variable that sent to your Event Listener file. So when receiver open that email or receive that email, you can have some variable that sent from that email to your Event Listener file. From that we can know the delivery status from email sent.

Let go to the practice.

First we need SendGrid account. You can register free in http://sendgrid.com/pricing.html.

When you already registered, then add some configuration to your environment using your SendGrid Username and Password.


ActionMailer::Base.smtp_settings = {
:address => "smtp.sendgrid.net",
:port => '25',
:domain => [your_domain],
:authentication => :plain,
:user_name => [your_sendgrid_username],
:password => [your_sendgrid_password]
}


Example


ActionMailer::Base.smtp_settings = {
:address => "smtp.sendgrid.net",
:port => '25',
:domain => 'example.com',
:authentication => :plain,
:user_name => 'username',
:password => 'password'
}


Now we need configure the email header. We need to download smtpapiheader.rb from http://wiki.sendgrid.com/doku.php?id=smtpapiheader.rb and save it to your model's folder.
On your mailer model.


class UserMailer < ActionMailer::Base

require 'smtpapiheader.rb'

def email(email)
setup_email(email)
@reply_to = "#{email.user.first_name} #{email.user.last_name} <#{email.user.email}>"
@from = "#{email.user.first_name} #{email.user.last_name} "
@subject = "A letter from #{email.user.first_name}"
content_type "text/html"
end

protected
def setup_email(email)
hdr = SmtpApiHeader.new()
receiver = email.email
hdr.addTo(receiver)
hdr.setUniqueArgs({:key => email.key})

header = hdr.asJSON()

@recipients = "#{email.email}"
@sent_on = Time.now
@headers["X-SMTPAPI"] = header
end

end


Now we need to create Event Listener file.
create some controller on your rails application.
I use email controller for this example.


class EmailController < ApplicationController

def receive_email_notification
if !params.blank? and !params[:key].blank? and !params[:email].blank? and !params[:event].blank?
email = Email.find_by_email_and_key(params[:email], params[:key])
if email
case params[:event]
when "open"
#add some logic when the listener receive notification
email.update_attribute(:send_status, params[:event])
when "click"
email.update_attribute(:send_status, params[:event])
when "unsubscribe"
email.update_attribute(:send_status, params[:event])
when "bounce"
email.update_attribute(:send_status, params[:event])
when "spamreport"
email.update_attribute(:send_status, params[:event])
end
end
@email = email
end
redirect_to :root unless email
end

end


Now add some line to your config/routes.rb


map.resources :emails,:collection => {:receive_email_notification => :post }


Now we need SendGrid to know the url our Event Listener. We need to log on to SendGrid.
On Home -> Developers -> Post Event URL (http://sendgrid.com/developer/postEventUrl).
On that page you can submit your url.
Example : http://example.com/emails/receive_email_notification

That's it. For more info about SendGrid http://sendgrid.com, for SendGrid API http://wiki.sendgrid.com/.

Monday, July 26, 2010

TinyMCE:Plugins - spellchecker on rails using aspell

TinyMCE:Plugins - spellchecker right now available on PHP Spellchecker. You can check latest TinyMCE Editor on http://tinymce.moxiecode.com/download.php.

Today I'll try to share about how to make spellchecker work on rails environment.

What we need are :
  • aspell
  • json gem
  • TinyMCE editor
  • spellchecker plugin

First we need aspell installed.

We can check it using terminal. Open terminal and type aspell.
aspell


How to install aspell
sudo apt-get install aspell


How to install json gem
sudo gem install json


Now we modify tiny_mce/plugins/spellchecker/editor_plugin.js
on init funtion search
g.url=f;


then replace it with
var re = new RegExp('^(?:f|ht)tp(?:s)?\://([^/]+)', 'im');
g.url='http://' + f.match(re)[1].toString();


then search
g.rpcUrl=e.getParam("spellchecker_rpc_url",this.url+'/rpc.php');


then replace it with
g.rpcUrl=e.getParam("spellchecker_rpc_url",this.url+'/spellcheck');


preview before edited

init:function(e,f){
var g=this,d;
g.url=f;
g.editor=e;
g.rpcUrl=e.getParam("spellchecker_rpc_url",this.url+'/rpc.php');
if(g.rpcUrl=="{backend}"){


after edited

init:function(e,f){
var g=this,d;
var re = new RegExp('^(?:f|ht)tp(?:s)?\://([^/]+)', 'im');
g.url='http://' + f.match(re)[1].toString();
g.editor=e;
g.rpcUrl=e.getParam("spellchecker_rpc_url",this.url+'/spellcheck');


Now we must add rails script for run aspell and return the value on json back to web. On this example I add it on HomeController.


class HomeController < ApplicationController

require 'json'

def spellcheck
raw = request.env['RAW_POST_DATA']
req = JSON.parse(raw)
lang = req["params"][0]
if req["method"] == 'checkWords'
text_to_check = req["params"][1].join(" ")
else
text_to_check = req["params"][1]
end
suggestions = check_spelling_new(text_to_check, req["method"], lang)
render :json => {"id" => nil, "result" => suggestions, "error" => nil}.to_json
return
end

private
def check_spelling_new(spell_check_text, command, lang)
json_response_values = Array.new
spell_check_response = `echo "#{spell_check_text}" | aspell -a -l #{lang}`
if (spell_check_response != '')
spelling_errors = spell_check_response.split(' ').slice(1..-1)
if (command == 'checkWords')
i = 0
while i < spelling_errors.length
spelling_errors[i].strip!
if (spelling_errors[i].to_s.index('&') == 0)
match_data = spelling_errors[i + 1]
json_response_values << match_data
end
i += 1
end
elsif (command == 'getSuggestions')
arr = spell_check_response.split(':')
suggestion_string = arr[1]
suggestions = suggestion_string.split(',')
for suggestion in suggestions
suggestion.strip!
json_response_values << suggestion
end
end
end
return json_response_values
end

end


Last action is add this to config/routes.rb
map.connect '/spellcheck', :controller => 'home', :action => 'spellcheck'