768x90 Getting Online Shouldn't be Tough- $7.49 .com Domains at Go Daddy
Showing posts with label Ruby. Show all posts
Showing posts with label Ruby. Show all posts

DateTime Range Helper In Rails View

There's some secret that you should know before you make time scaling in ruby on rails specially to the view. I have little smile when seeing helper from a developer that make time helper like in twitter or facebook, example a moment ago, or 3 minutes ago, or 1 hour ago. Why you hurt your brain if Rails already supports it. I think that he doesnt know the secret, now let me tell you the secret:

distance_of_time_in_words_to_now
Reports the approximate distance in time between from Time to time now. Set include_seconds to true if you want more detailed approximations when distance less than 1 min.  example :

<%=  distance_of_time_in_words_to_now(from_time, include_seconds =  false) %> 

distance_of_time_in_words
This is the same like above, but you can get range of time from 2 dateTimes, example :
<%=  distance_of_time_in_words_to_now(from_time, to_time = 0, include_seconds = false, options = {}) %>

below is table list from date range in many conditions:
0  - 29 secs # => less than a minute
30 secs to 1 min, 29 secs # => 1 minute
1 min, 30 secs to; 44 mins, 29 secs # => [2..44] minutes
44 mins, 30 secs to 89 mins, 29 secs # => about 1 hour
89 mins, 29 secs to 23 hrs, 59 mins, 29 secs # => about [2..24] hours
23 hrs, 59 mins, 29 secs to 47 hrs, 59 mins, 29 secs # => 1 day
47 hrs, 59 mins, 29 secs to 29 days, 23 hrs, 59 mins, 29 secs # => [2..29] days
29 days, 23 hrs, 59 mins, 30 secs to 59 days, 23 hrs, 59 mins, 29 secs # => about 1 month
59 days, 23 hrs, 59 mins, 30 secs to 1 yr minus 1 sec # => [2..12] months
1 yr to 1 yr, 3 months # => about 1 year
1 yr, 3 months to 1 yr, 9 months # => over 1 year
1 yr, 9 months to 2 yr minus 1 sec # => almost 2 years
2 yrs to max time or date # => (same rules as 1 yr)

Rainbow for Slow Rack Application

Rainbows! is an HTTP server for sleepy Rack applications. It is based on Unicorn, but designed to handle applications that expect long request/response times and/or slow clients. For Rack applications not heavily bound by slow external network dependencies, consider Unicorn instead as it simpler and easier to debug.

Rainbows is mainly designed for the odd things Unicorn sucks at:

  • Web Sockets (via Sunshowers)
  • 3rd-party APIs (to services outside your control/LAN)
  • OpenID consumers (to providers outside your control/LAN)
  • Reverse proxy implementations with editing/censoring (to upstreams outside your control/LAN)
  • Comet
  • BOSH (with slow clients)
  • HTTP server push
  • Long polling
  • Reverse AJAX
  • real-time upload processing (via upr)
    Rainbows can also be used to service slow clients directly even with fast applications. 

 You may also install it via RubyGems on RubyGems.org
gem install rainbows

for Rack applications

In APP_ROOT, run:
rainbows
 
PS: For more information about tunning you can read here  

Develop SmartPhone Using RhoHub

RhoMobile is a first Development as a Service for Mobile, RhoHub or RhoMobile lets you quickly create native apps in Ruby and HTML for all major smartphones using the award-winning Rhodes framework. RhoHub provides a hosted RhoSync server to synchronize backend data with your users' smartphones.Writing an app on RhoHub consists of generating a set of objects, editing the client side (Rhodes framework) code, the server side (RhoSync) source adapter and building for your target smartphones. Below is an overview of RhoHub's rich IDE and other services.



  1. Debugging Console : Use the collapsible console to quickly view output from your RhoSync source adapters.
  2. File Manager : Navigate and modify your app's files in a simple view.
  3. Rich Editor : Use the powerful Ruby/HTML/CSS/Javascript editor right from your browser, or work locally and upload your app.
  4. Text Search :  Search for text in all files of your app.
  5. Toolbar & Quick Links :  Access all of RhoHub's productivity tools right from the editor.




What you can do in RhoHub ?

RhoHub provides you 3 packages, Free, Basic and Premium. You can start with free 50MB Disk Space.

Import contact information in Google Spreadsheet To Google Contact Using Rake

This March, I had a sexy task to import all employees and departments contacts information which were stored in Google Spreadsheet into Google contact.

A dummy people will think to pay data entry for entering them through google contact form. Whoa.. if i were a data entry, i would have had broken fingers after entering all data. Any way, I found a shortcut to import all data in only seconds or minutes, that is; make a robot to enter all data when we have a lunch.

Now, let's prepare the tools :

1. Installed Ruby on Rails Application
2. gem install gdata
3. gem install google-spreadsheet-ruby
4. open any text editor

Create Basic Rake Frame


namespace :db do

desc "GS2C: Google spreadsheet to Google contact"
task :gs2c => :environment do
require 'gdata'
require 'google_spreadsheet'

#Here will be some sexy scripts

end

end



Here it is, The Robot

namespace :db do

desc "GS2C: Google spreadsheet to Google contact"
task :gs2c => :environment do
require 'fastercsv'
require 'gdata'
require 'google_spreadsheet'

#sample spreadsheet URL
#https://spreadsheets.google.com/a/kiranatama.com/ccc?key=0AlQZq7IIjE6UdF92SkhRazlYaVFUWFNYZGxxLWpoT0E&hl=en

#settings
@spreadsheet_key = "0AlQZq7IIjE6UdF92SkhRazlYaVFUWFNYZGxxLWpoT0E"
login_config = YAML.load_file("#{RAILS_ROOT}/config/google_login.yml")[RAILS_ENV]
login_config["google"].each { |key, value| instance_variable_set("@#{key}", value) }

def create_spreadsheet_connector
@google_spreadsheet = GoogleSpreadsheet.login(@email_contact, @password_contact)
create_contact_connector
end

def create_contact_connector
@google_contact = GData::Client::Contacts.new({
:authsub_scope => 'http://www.google.com/m8/feeds/',
:source => 'google-DocListManager-v1.1',
:version => '3.0'})
@google_contact.clientlogin(@email_contact, @password_contact)
create_contact_entry
end

def create_contact_entry
@contact_entry = <<-EOF
<atom:entry xmlns:atom='http://www.w3.org/2005/Atom'
xmlns:gd='http://schemas.google.com/g/2005'>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/contact/2008#contact' />
EOF
start_load_csv
end

def start_load_csv
@spreadsheet = @google_spreadsheet.spreadsheet_by_key(@spreadsheet_key)
#Sample Row Header / First Row
#First Name | Last Name | Email | Work Phone | Home Phone | Address | City | State | Country | ZIP
#You have to skip first row and blank row
i = 0
@spreadsheet.worksheets do |row|
if i < 1
i++
return
end
@google_contact.post( 'http://www.google.com/m8/feeds/' + 'contacts/default/base?v=3', create_google_contact(row,i))
i++
end
end

def create_address(address,city,state,country,zip)
address = <<-EOF
<gd:postalAddress rel='http://schemas.google.com/g/2005#home' primary='true'>
#{address}
#{city}
#{state}, #{zip}
#{country}
</gd:postalAddress>
EOF
return address
end

def create_google_contact(row,i)
first_name = row[i, 1].blank? ? "---" : row[i, 1]
last_name = row[i, 1].blank? ? "---" : row[i, 2]
email = row[i, 3].blank? ? "---" : row[i, 3]
work_phone = row[i, 4].blank? ? "---" : row[i, 4]
home_phone = row[i, 5].blank? ? "---" : row[i, 5]
address = row[i, 6].blank? ? "---" : row[i, 6]
city = row[i, 7].blank? ? "---" : row[i, 7]
state = row[i, 8].blank? ? "---" : row[i, 8]
country = row[i, 9].blank? ? "---" : row[i, 9]
zip = row[i, 10].blank? ? "---" : row[i, 10]
full_name = first_name + last_name

data = <<-EOF
#{@contact_entry}
<title>#{full_name}</title>
<atom:content type='text'>#{contact.note}</atom:content>
<gd:name>
<gd:fullName>#{full_name}</gd:fullName>
<gd:givenName>#{first_name}</gd:givenName>
<gd:familyName>#{last_name}</gd:familyName>
</gd:name>

<gd:email primary='true' rel='http://schemas.google.com/g/2005#home' address='#{email}'/>
<gd:phoneNumber rel='http://schemas.google.com/g/2005#home'>#{home_phone}</gd:phoneNumber>
<gd:phoneNumber rel='http://schemas.google.com/g/2005#work'>#{work_phone}</gd:phoneNumber>

#{create_address(address,city,state,country,zip)}

</atom:entry>
EOF
return data
end

create_spreadsheet_connector

end

end


Command Line : rake db:gs2c or rake -T

Create and Update Google Contact from Ruby without Batch

There's less information about ruby on rails method in google contact. I would like to share you about how to export new google contact / create new google contact from our table contacts through Ruby.

in my contacts_controller.rb, i wrote this script


class ContactsController < ApplicationController
require 'yaml'
require 'cgi'
before_filter :prepare_google_contact, :expect => [:create, :update]
CONTACTS_SCOPE = 'http://www.google.com/m8/feeds/'

def create
@contact = Contact.new(params[:contact])

respond_to do |format|
if @contact.save
feed = @google_contact.post( CONTACTS_SCOPE + 'contacts/default/base', google_contact(@contact)).to_xml
@contact.update_attribute(:google_contact_id, feed.elements['id'].text)
flash[:notice] = 'Contact was successfully created.'
format.html { redirect_to(@contact) }
format.xml { render :xml => @contact, :status => :created, :location => @contact }
format.fxml { render :fxml => @contact }
else
format.html { render :action => "new" }
format.xml { render :xml => @contact.errors, :status => :unprocessable_entity }
format.fxml { render :fxml => @contact.errors }
end
end
end

# PUT /contacts/1
# PUT /contacts/1.xml
# PUT /contacts/1.fxml
def update
@contact = Contact.find(params[:id])
@saved = @contact.update_attributes(params[:contact])

respond_to do |format|
if @saved
@google_contact.headers = {'If-Match'=>'*'}
feed = @google_contact.put(@contact.google_contact_id,
create_google_contact(@contact.reload())).to_xml
flash[:notice] = 'Contact was successfully updated.'
format.html { redirect_to(@contact) }
format.xml { head :ok }
format.fxml { render :fxml => @contact }
else
format.html { render :action => "edit" }
format.xml { render :xml => @contact.errors, :status => :unprocessable_entity }
format.fxml { render :fxml => @contact.errors }
end
end
end

private

def prepare_google_contact
contact_setup = YAML.load_file("#{RAILS_ROOT}/config/contact.yml")
contact_setup["google"].each { |key, value| instance_variable_set("@#{key}", value) }
@google_contact = GData::Client::Contacts.new({
:authsub_scope => 'http://www.google.com/m8/feeds/',
:source => 'google-DocListManager-v1.1',
:version => '3.0'})
session[:token_contact] = @google_contact.clientlogin(@email_contact, @password_contact)
@contact_entry = <<-EOF
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:contact="http://schemas.google.com/contact/2008"
xmlns:gd="http://schemas.google.com/g/2005">

<category term='http://schemas.google.com/contact/2008#contact'
scheme='http://schemas.google.com/g/2005#kind'/>
EOF

session[:token_contact] = @google_contact.clientlogin(@email_contact, @password_contact)
end

def google_contact(contact)
data = <<-EOF
#{@contact_entry}
<title>#{contact.first_name}</title>
<content>#{contact.note}</content>
<gd:name>
<gd:fullName>#{contact.first_name}</gd:fullName>
</gd:name>
<gContact:birthday when='#{contact.birth_day}'/>
<gd:email primary='true' rel='http://schemas.google.com/g/2005#home' address='#{contact.email}'/>
<gd:phoneNumber rel='http://schemas.google.com/g/2005#mobile'>#{contact.mobile}</gd:phoneNumber>
<gd:phoneNumber rel='http://schemas.google.com/g/2005#work'>#{contact.phone}</gd:phoneNumber>
<gd:structuredPostalAddress rel='http://schemas.google.com/g/2005#home'>
<gd:formattedAddress>#{contact.street}
#{contact.city}
#{contact.province}, #{contact.zipcode}
#{contact.country}
</gd:formattedAddress>
</gd:structuredPostalAddress>
</entry>
EOF
return data
end

end


in this study case I put my login google information in config/contact.yml file like this :


google:
email_contact: yacobus.r@kiranatama.com
password_contact: dec.07.1982


and here is my contact migration script lines :

class CreateContacts < ActiveRecord::Migration
def self.up
create_table :contacts do |t|
t.string :first_name
t.string :middle_name
t.string :last_name
t.string :phone
t.string :mobile
t.string :email
t.string :street
t.string :province
t.string :zipcode
t.string :city
t.string :country
t.string :note
t.string :type
t.string :google_contact_id
t.timestamps
end
end

def self.down
drop_table :contacts
end
end


and of course you have to install gem install gdata

Do not confuse about "format.fxml" this is respond data type for Restfulx (Flex/Air Framework).

Simple right !! but when this written's published, google still not release how to create and update trough ruby on rails. And many developer stucked because google provided create and update contact trough Batch method.

Anti Spam Email For Your Rails Page with Javascript

In your view : <%= js_antispam_email_link('username@domain.com') %>


Code for your helper


# Takes in an email address and (optionally) anchor text,

# its purpose is to obfuscate email addresses so spiders and

# spammers can't harvest them.

def js_antispam_email_link(email, linktext=email)

user, domain = email.split('@')

user = html_obfuscate(user)

domain = html_obfuscate(domain)

# if linktext wasn't specified, throw encoded email address builder into js document.write statement

linktext = "'+'#{user}'+'@'+'#{domain}'+'" if linktext == email

rot13_encoded_email = rot13(email) # obfuscate email address as rot13

out = "#{linktext}&lt;br/&gt;&lt;small&gt;#{user}(at)#{domain}&lt;/small&gt;\n" # js disabled browsers see this

out += "// <![CDATA[

\n"

out += " \n"

out += " string = '#{rot13_encoded_email}'.replace(/[a-zA-Z]/g, function(c){ return String.fromCharCode((c = (c = c.charCodeAt(0) + 13) ? c : c - 26);});\n"

out += " document.write('#{linktext}'); \n"

out += " //\n"

out += "

// -->

// ]]>\n"

return out

end


private

# Rot13 encodes a string

def rot13(string)

string.tr "A-Za-z", "N-ZA-Mn-za-m"

end


# HTML encodes ASCII chars a-z, useful for obfuscating

# an email address from spiders and spammers

def html_obfuscate(string)

output_array = []

lower = %w(a b c d e f g h i j k l m n o p q r s t u v w x y z)

upper = %w(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)

char_array = string.split('')

char_array.each do |char|

output = lower.index(char) + 97 if lower.include?(char)

output = upper.index(char) + 65 if upper.include?(char)

if output

output_array << "&##{output};"

else

output_array << char

end

end

return output_array.join

end

Track Total Coverage of Your Test Unit Code with RCOV

Hi All :

I just want share my testing with Ruby coverage code or Rcov. It is fun (for me, dont know for others) playing with Rcov report, i think it is like bugs tracking but i dont know other people called it or maybe it is like tool to coverage test your application codes.

First think you have to do is installing the gem :

gem install rcov

and then write simple code to run it as rake then save it in your_app/lib/tasks :

require 'rcov/rcovtask'

namespace :test do
namespace :coverage do

desc "Delete aggregate coverage data."

task(:clean) { rm_f "coverage.data" }
end

desc 'Aggregate code coverage for unit, functional and integration tests'

task :coverage => "test:coverage:clean"

%w[unit functional integration].each do |target|

namespace :coverage do

Rcov::RcovTask.new(target) do |t|
t.libs << "test"
t.test_files = FileList["test/#{target}/*_test.rb"]
t.output_dir = File.dirname(__FILE__)+"/report_rcov/#{target}"
t.verbose = true
t.rcov_opts << '--rails --aggregate coverage.data'
end
end

task :coverage => "test:coverage:#{target}"

end

system(" \"C:/Program Files/Mozilla Firefox/firefox.exe\" " +
"file:///"+File.dirname(__FILE__)+"/report_rcov/unit/index.html")

end


Absolutly i am using windows if you are using another OS not windows you could change the 4th line from bottom to :

system(open File.dirname(__FILE__)+"/report_rcov/unit/index.html")


Open your shell or CMD then execute rake test:coverage or open rake -T

rake test:coverage # Aggregate code coverage for unit,...
rake test:coverage:clean # Delete aggregate coverage data.
rake test:coverage:clobber_functional # Remove rcov products for functional
rake test:coverage:clobber_integration # Remove rcov products for integration
rake test:coverage:clobber_unit # Remove rcov products for unit
rake test:coverage:functional # Analyze code coverage with tests ...
rake test:coverage:integration # Analyze code coverage with tests ...
rake test:coverage:unit # Analyze code coverage with tests ...



Here I attached sample report from rcov. I hope this written can be useful for you gentleman and ladies.

Step by step to deploy application using SVN and Capistrano

Here process deploying of application in a hosting (in this case i deploy my application in FastCGI on HostingRails.com). There are 3 major steps of deployment :


  1. Create SVN Repository (Next I will explain about GIT)
  2. Setup Capistrano & Deploy Application with Capistrano


Create SVN Repository

  • Create REPOSITORY to your hosting account, please ensure that your hosting is already installed capistrano & SVN or ask your hosting admin/support to install SVN and Capistrano.
username@mydomain.com [~]$ mkdir -p ~/svn/your_app_name
username@mydomain.com [~]$ svnadmin create ~/svn/your_app_name
username@mydomain.com [~]$ mkdir -p ~/tmp/your_app_name/{tags,branches,trunk}
username@mydomain.com [~]$ svn import ~/tmp/your_app_name file:///home/username/svn/your_app_name -m "Created Repository"

  • At this point you have enough setup on your Hosting account for single-user access to Subversion. You can now check out your repository at:
username@mydomain.com [~]$ svn co svn+ssh://username@mydomain.com/home/username/svn/your_app_name/trunk

  • Next we are going to add your existing Rails app to the Subversion repository. If you don't have an existing app, you will need to create one.
username@mydomain.com [~]$ svn co svn+ssh://username@mydomain.com/home/username/svn/your_app_name/trunk your_app_name_dev

  • Ok, it looks fine if you do right. The next step is copy your application for repository. Before this process, upload your existing application folder to your host in zip or tar.gz file. After uploaded, extract it to up folder of public_html (do not extract your application in public_html). After extracting, we will modify some data and permission file.

  • Your database.yml(.online) file simply needs to look like this:

production:
 adapter: mysql
 database: [your_hosting_username]_[your_database_name]
 username: [your_hosting_username] OR [your_hosting_username]_[your_database_name]
 password: your_password


  • And in your environment.rb(.online) file you'll just need to uncomment the following line to confirm you're in production mode:
ENV['RAILS_ENV'] ||= 'production'

  • Make sure your .htaccess file sends requests to dispatch.fcgi. Please Note - as of Rails 2.1.0 the .htaccess file no longer exists in the default skeleton.  Run a "rails _2.0.2_ testapp" and move over the public/.htacess from there.  This one is easy but also critically important.   In your local Rails application's public/.htaccess file change the :

RewriteRule ^(.*)$ dispatch.cgi [QSA,L]

  • EXACTLY where it is already in the file, don't change its position, to: 
RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]

  • also - very important make sure the 'AddHandler fastcgi-script .fcgi' is commented out at the top of your .htaccess:  
    # General Apache options
    # AddHandler fastcgi-script .fcgi
    And that's it

  • Now look into public folder and edit all files with name "dispatch" (they are 3 files), edit the first line and change to :
#!/usr/local/bin/ruby

  • Do not forget to change permission into 755 for all files in public folder specially all dispatch.* files and .htaccess.

  • Next, you will need to copy your existing Rails app on your local machine into the version we just checked out
username@mydomain.com [~]$ cp -R your_app_name/* your_app_name_dev

  • Now you can see if Subversion recognizes the updated files and directories:
username@mydomain.com [~]$ cd your_app_name_dev
username@mydomain.com [~/your_app_name_dev]$ svn status

  • You should get something like this:

?      test
?      app
?      tmp
?      log
?      Rakefile
?      script
?      components
?      config
?      db
?      doc
?      lib
?      README
?      vendor
?      public


  • Now, just add them to the repository:

username@mydomain.com [~/your_app_name_dev]$ svn add test app tmp log Rakefile script components config db doc lib README vendor public

  • You will see a list of the files that were added with an 'A' next to indicating that the files will be added on the next commit. You will see something like this:

A         test
A         test/fixtures
A         test/fixtures/contact_mailer
A         test/fixtures/contact_mailer/notify
A         test/fixtures/contact_mailer/validate_email
A         test/fixtures/contacts.yml
A         test/functional
A         test/functional/website_controller_test.rb
A         test/integration
# and so on


  • Next, lets commit the Rails app to the repository
username@mydomain.com [~/your_app_name_dev]$ svn commit -m "Added The Application"

  • This may take a few minutes depending on the size of your application. You will see the list of files appear again followed by this:
  • Transmitting file data .................................................................
    Committed revision 2.

  • Now your will be able to edit your code on your local machine and have the changes reflected in newer revisions simply by adding and committing files.


Setup Capistrano & Deploy Application


  • Setup your Rails application to work with Capistrano. Once you have checked out your code from the svn repository, change to the root of the Rails app on your development machine and run (look carefully there is a dot after capify command, just type it completely with a dot):

    username@mydomain.com [~/your_app_name_dev]$ capify .

    # This is the output
    [add] writing `./Capfile'
    [add] writing `./config/deploy.rb'
    [done] capified!
    Capistrano created two files: /config/deploy.rb and Capfile. (Note: /config/deploy.rb might have been skipped if you already had a deploy.rb file in your app.) The config/deploy.rb file will contain your application variables used to deploy your app, while the Capfile will contain your deployment tasks.


  • So open the deploy.rb file and we'll start customizing the deployment process. The first thing we want to do is set our application variables. So let's modify this first section of the file:

set :application, "your_app_name"   set :domain, "mydomain.com"  set :user, "username"        set :repository,  "svn+ssh://#{user}@#{domain}/home/#{user}/svn/#{application}/trunk"  set :use_sudo, false     set :deploy_to, "/home/#{user}/#{application}"   set :deploy_via, :checkout set :chmod755, "app config db lib public vendor script script/* public/disp*"  set :svn_username, "username" set :svn_password, "hosting_password" set :password, "hosting_password" default_run_options[:pty] = true ssh_options[:keys] = %w(/Path/To/id_rsa) role :app, "mydomain.com" role :web, "mydomain.com"
role :db, "mydomain.com", :primary => true

  • Now that everything is in place, you can commit your changes to the Subversion repository if you want:

    username@mydomain.com [~/your_app_name_dev]$ svn add config/deploy.rb Capfile
    username@mydomain.com [~/your_app_name_dev]$ svn commit -m "Configured application for Capistrano"

  • Last Step - Setup Your Hosting Account. Next we need to setup our Hosting account. This is where our hard work pays off with Capistrano. From your local machine enter the following commands:
username@mydomain.com [~/your_app_name_dev]$ cap setup


  • Next you need to run a cold deploy.

username@mydomain.com [~/your_app_name_dev]$  cap cold_deploy


  • Next we can do a full deploy

username@mydomain.com [~/your_app_name_dev]$  cap deploy


  • Or if you want Capistrano to run your migration files (be sure to have your database and database.yml setup properly).

username@mydomain.com [~/your_app_name_dev]$  cap deploy_with_migrations


  • If you ever run into problems and need to rollback to a previous revision of your code simple enter:

username@mydomain.com [~/your_app_name_dev]$  cap rollback


  • As you make revisions to your code on your local machine and are ready to deploy your updated application to the production server all you have to do is:

username@mydomain.com [~/your_app_name_dev]$ $ svn commit -m "Your Custom Reference Message";cap deploy


How to use find_by_sql without Model

many cases, we use model to use find_by_sql like ModelName.find_by_sql, but now how we can find_by_sql without mode?

ActiveRecord::Base.connection.execute 'select * from users'

To return array of hashes, you can use it :

ActiveRecord::Base.connection.select_all

.


Translation for your Ruby on Rails App



I am writing this article with accompanied by a cup of coffee while waiting MU Vs Chealsea for Champion Final. Back to the topic. You should know many familiar online translation like google and altavista. Now i will like to introduce you about gibberish in rails. Let start it :

  • Install the plugin to your app rails.
ruby script/plugin install http://svn.myutil.com/projects/plugins/gibberish_rails/
or
ruby script/plugin install svn://errtheblog.com/svn/plugins/gibberish
  • After that go to your Application_controller.rb then use arround_filter for implementation of gibberish :
class ApplicationController < ActionController::Base
around_filter :set_language

private
def set_language
Gibberish.use_language(session[:language]) { yield }
end
end
  • Another method is described in README file. Like :
class ApplicationController < ActionController::Base
around_filter :use_best_guess_locale

private
def use_best_guess_locale
session[:locale] = GibberishRails.best_guess_locale(params[:locale], request.env['HTTP_ACCEPT_LANGUAGE']) if ( ! session[:locale] || params[:locale] || RAILS_ENV == 'development' )

Gibberish.use_language(session[:locale]) {yield}
end
end
  • To create new dictionary, you can create it in YAML file such as es.yaml :
welcome_friend: ¡Recepción, amigo!
welcome_user: ¡Recepción, {user}!
love_rails: Amo los carriles.



_

Simple & Awesome Rails Form

How to create Simple, fast and awesome rails form in your rhtml or html.erb ? the answer for now is Super_In_Place_Controls & I tested in Rails 2.0. Let start to use it :

  • Install the plugin to your ruby app
ruby script/plugin install http://os.flvorful.com/svn/plugins/super_in_place_controls

  • In your layout or rhtml / html.erb put it :
<%= stylesheet_link_tag 'in_place_styles' %>

  • Done !!, let start to implement it in your view file (click the image below to enlarge).
  • For regular text_field you can change it to be :
in_place_text_field :product, :title

  • For regular text_area, you can change it to be :
in_place_text_area :product, :description

  • For regular select_tag, you can change it to be:
in_place_select :product, :product_type, :choices => %w(Awesomeness Coolness Phatness RubyBliss).map { |e| [e, e] }

  • For regular radio_collection, you can change it to be :
in_place_radio :product, :price, :choices => %w(199 299 399 499 599 699 799 899 999).map { |e| [e, e] }

  • For check box collection you can change it to be:
in_place_check_box :product, :category_ids, :choices => Category.find(:all).map { |e| [e.id, e.title] }, :display_text => :collection

  • And for date you can change to be :
in_place_date_select :product, :display_begin

  • for more style you can addcalendar_date_select_includes "blue" to the pages you want to use the calendar select on. The other styles for the calendar_date_select are "blue", "plain", "red", "silver", "default".

Create Realtime World News in Your Site

What could you do if you had access to the world’s news, and had a standardized and rational way to get quick responses to rich queries about what’s happening in the world? What could you build if you could incorporate dynamic, global, continually refreshed, high quality content into your applications, widgets, and websites? You should have many answers. But I have only 1 act, I will smileproudly. :D. Let's start to implement it by using Ruby on Rails:

  • Download this code and paste it to your app_name/lib folder
  • Then in your controller, put it :
require 'daylife'
a = Daylife::API.new('your api key','sharedsecret')
r = a.execute('search','getRelatedArticles', :query => 'sam adams', :limit => 5)
if(r.success?)
r.articles.each {|a| puts a.headline }
puts r.articles[1].source.daylife_url
else
# output the error message
puts "Error: #{r.code}: #{r.message}"
end
  • Now your dream comes true to have site like Yahoo News or at least like daylife.com
  • Has been tested and working nice :D

Snapshot Web Page trough Ruby

Some times, newbie question is valuable for me. Thanks for some one who asked about Snapshot a webpage in ruby by providing web url. Let see it :

  • Sign Up a free account HERE
  • Get Your API Key, after logged in.
  • Create a New File in your Model with name snapweb.rb, than paste code below inside :
require 'net/http'
require 'rubygems'
require 'xmlsimple'

class Snapweb

@@api_baseurl = 'http://webthumb.bluga.net/api.php'
@@api_key = 'fc52f8bdb9e5b86f8150a145d5c8fd97'

attr_accessor :collection_time, :job_id, :ok

def initialize(url, width = 1024, height = 768)
#for safety url you can uncomment it :
#url = url.gsub(/&/, '& a m p ;')
#please delete space in '& a m p ;'

api_request = %Q{<webthumb><apikey>#{@@api_key}</apikey><request><url>#{url}</url><width>
#{width}</width><height>#{height}</height></request></webthumb>}

result = do_request(api_request)

if result.class == Net::HTTPOK
result_data = XmlSimple.xml_in(result.body)
@job_id = result_data['jobs'].first['job'].first['content']
@collection_time = Time.now.to_i + result_data['jobs'].first['job'].first['estimate'].to_i
@ok = true
else
@ok = false
end
end

def retrieve(size = :small)
api_request = %Q{<webthumb><apikey>#{@@api_key}</apikey><fetch><job>#{@job_id}</job><size>
#{size.to_s}</size></fetch></webthumb>}
result = do_request(api_request)
result.body
end

def retrieve_to_file(filename, size = :small)
File.new(filename, 'wb+').write(retrieve(size.to_s))
end

def ready?
return unless Time.now.to_i >= @collection_time

api_request = %Q{<webthumb><apikey>#{@@api_key}</apikey><status><job>#{@job_id}</job></status></webthumb>}
result = do_request(api_request)

if result.class == Net::HTTPOK
@ok = true
result_data = XmlSimple.xml_in(result.body)
begin
@result_url = result_data['jobStatus'].first['status'].first['pickup']
@completion_time = result_data['jobStatus'].first['status'].first['completionTime']
rescue
@collection_time += 60
return false
end
else
@ok = false
end

true
end

def ok?
@ok == true
end

def wait_until_ready
sleep 1 until ready?
end

private

def do_request(body)
api_url = URI.parse(@@api_baseurl)
request = Net::HTTP::Post.new(api_url.path)
request.body = body
Net::HTTP.new(api_url.host, api_url.port).start {|h| h.request(request) }
end
end

  • After that in your controller, put it :

class TeapociController < ApplicationController

def index

web_pict = Snapweb.new("http://teapoci.blogspot.com")

if web_pict.ok?
web_pict.wait_until_ready web_pict.retrieve_to_file("#{RAILS_ROOT}/public/images/teapoci_1.jpg", :small)
web_pict.retrieve_to_file("#{RAILS_ROOT}/public/images/teapoci_2.jpg", :medium)
web_pict.retrieve_to_file("#{RAILS_ROOT}/public/images/teapoci_3.jpg", :medium2)
web_pict.retrieve_to_file("#{RAILS_ROOT}/public/images/teapoci_4.jpg", :large)

flash[:notice] = "Thumbnails saved"

else
flash[:notice] = "Error"
end

end
end

  • Now you have the screenshot images at folder /public/images/

Enjoy & Good Luck!!!

Thanks to : Josh

Live Validation Field with AJAX

LiveValidation is a small open source javascript library for making client-side validation quick, easy, and powerful. It comprises of two main parts. Firstly, it provides developers with a rich set of core validation methods, which can also be used outside the context of forms. Secondly, it provides your visitors with real-time validation information as they fill out forms, helping them to get it right first time, making the forms easier, quicker and less daunting to complete.

The naming conventions and parameters of the validations are similar to those found in the Ruby on Rails framework, and as such is the perfect client-side companion. Don’t worry if you dont use Ruby on Rails though, LiveValidation can be used anywhere you like, is simple to learn, and a joy to use.

Two versions are provided - a prototype.js version (ideal for use with Rails), and a standalone version (for using with any other javascript framework, or when having one at all would be overkill). Both are fully tested on most modern browsers with a comprehensive test suite.

So take a look around, download it, and make some forms (for) fun!

Check this out : LIVEVALIDATION.com

 
powered by Blogger