Showing posts with label Ruby on Rails(RoR). Show all posts
Showing posts with label Ruby on Rails(RoR). Show all posts

Tuesday, April 12, 2011

SHARE - Client OS Detection

    <%= request.env['HTTP_USER_AGENT'] %>
    <%= request.env['HTTP_USER_AGENT'] =~ /Linux/ %>
    <%= request.env['HTTP_USER_AGENT'] =~ /Windows/ %>
    <%= request.env['HTTP_USER_AGENT'] =~ /Mac/ %>
    <%= request.env['HTTP_USER_AGENT'] =~ /iPhone/ %>

SHARE - How to get mp3 information (id3v1 and id3v2 tags) using ruby-mp3info

how to install gem
    gem install ruby-mp3info
how to use
    require "mp3info"
    begin
      mp3=Mp3Info.open(file_full_path)
      mp3.tag.title
      puts mp3.tag.artist  
      puts mp3.tag.album
    rescue Exception => e
      puts e.inspect
    end
for more information you can see here
http://ruby-mp3info.rubyforge.org/

SHARE - How to get image information using RMagick

    require 'RMagick'
    include Magick
    begin
      image=Image.read(pic_full_path).first
      image.filename #filename
      image.filesize #filesize
      image.columns #width
      image.page.width #width
      image.rows #height
      image.page.height #height
    rescue Exception => e
      puts e.inspect
    end

Friday, February 11, 2011

SHARE - TruliaMap integration

One of my client want add TruliaMap 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.

What you need to make it work are latitude, langitude and zipcode for the place we want to search

add this to your controller

require 'open-uri'
require 'openssl'

url = "http://maps.googleapis.com/maps/api/geocode/xml?address=#{((community.name.to_s+' ')+(community.city.name.to_s+' ' if community.city)+(community.state.code.to_s+' ' if community.state)+(community.zipcode.zip.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


add this to your view

<div class='show-safety'>
<br/>
<div id="truliamap" style="font-family:arial,verdana;text-align:center; width:350px; height:380px; background-color:B5CF5A;">
<!--<div id="truliamap_header" style="color:;font-weight:bold;font-size:14px;padding:1px;height:16px;">Distinctive Properties</div>-->
<p style="margin:0px;padding:0px;line-height:0px;">
<iframe style="border:none; padding:0px; width:340px; height:329px;" frameborder="0" width="340" height="329" scrolling="no"
src="http://truliamap.trulia.com/truliamapapi/?a=5fa9ac&u=fd63b6&sid=&cv=&v=map&d=source&lat=<%= @lat -%>&lng=<%= @lng -%>&s=large&r=&city=&state=&uid=&zip=<%= community.zipcode.zip.to_s -%>">your browser not compatible</iframe>
</p>
<div style="margin-left:5px;margin-right:5px;text-align:left;font-size:11px;">
<div style="float:left;width:100px;">
<a id="map_signup" href="http://www.trulia.com/tools/map/" target="_blank" style="color:;">Get your own TruliaMap</a></div>
<div id="map_logo" style="float:right;width:79px;cursor:pointer;">
<a href="http://www.trulia.com/" target="_blank">
<img name="mmlogo" id="mmlogo" style="padding:0px; margin:0px;border-width:0px;" src="http://static.trulia-cdn.com/images/map/mm/logo-grn.gif" border="0" alt="Real Estate Search">
</a>
</div>
</div>
</div>
</div>

You can generate the code here http://www.trulia.com/tools/map/

SHARE - How to calculate how much brighness from color

My client ask me about how to make text black or white color base on background color for that text.

example:

- background color black, color of text is white
- background color white, color of text is black
- background color yellow, color of text is black
- background color dark-purple, color of text is white

I think I need to calculate how much brighness from background color that used.

After googling I found this formula for calculating brighness.

brightness = sqrt( .241 R2 + .691 G2 + .068 B2 )

R = red color (decimal)
G = green color (decimal)
B = blue color (decimal)

example:
   
background color : EA0516, text color : FFFFFF
backgorund color : FFFF00, text color : 000000

on my model

class model

def self.calculate_brightness(color) #format color on hex without #, example FFFFFF
r = color[0..1].hex
g = color[2..3].hex
b = color[4..5].hex
value = Math.sqrt(r * r * 0.241 + g * g * 0.691 + b * b * 0.068)
(value < 130 ? 'FFFFFF' : '000000')
end

end

You can see more information here
http://alienryderflex.com/hsp.html
http://www.nbdtech.com/Blog/archive/2008/04/27/Calculating-the-Perceived-Brightness-of-a-Color.aspx

SHARE - How to get content from Outside.in

Outside.in is the leading provider of hyperlocal news and information. Outside.in show consumers neighborhood news and information from local bloggers, journalists and mainstream media on hundreds of trusted news sites across the Outside.in Network including CNN.com as well as www.outside.in


We can get the stories using this example. I add this on LocalNews class.

class LocalNews < ActiveRecord::Base

@key = 'f889ntmabe5mjqr9dzd2a7ce'
@secret = 'yZM6nU4zGR'

require 'open-uri'
require 'openssl'
require 'md5'

def self.generate_key
"dev_key=#{@key}&sig=#{MD5.new(@key + @secret + Time.now.to_i.to_s).hexdigest}"
end

def self.generate_url_from_zipcode(zipcode, oi_key, limit)
'http://hyperlocal-api.outside.in/v1.1/zipcodes/'+zipcode.to_s+'/stories?'+oi_key+(limit.nil? ? '' : '&limit='+limit.to_s)
end

def self.get_content(zipcode, limit=20)
oi_key = generate_key
url = generate_url_from_zipcode(zipcode, oi_key, limit)
open_url = open(url) rescue nil
return '' if open_url.nil?
json = open_url.read

contents = JSON.parse(json)
end
end


We can get stories using command like this

LocalNews.get_content(12345)


We can limit our stories to some number using command like this

It'll get 5 stories.

LocalNews.get_content(12345, 5)


I use Json to parse the stories.

SHARE - How to know file that generated using background job already created or not

Sometimes we need to know file that generated using background job already created or not.

We can check that file already exist, readable and created using this method.

We can use this to check file already exist or not

File.exist?(file_path)
#true if file exist
#false if not exist



We can use this to check file readable or not

File.readable?(file_path)
#true if file readable
#false if not readable


We need this to check file already finish created or not

File.zero?(file_path)
#true if file exist but not yet finish created
#false if file exist and already created

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

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'