Monday, December 14, 2009

Getting wired and wireless working on ubuntu 9.0.4

by sandipransing 0 comments
It might be the case that earlier wireless was working and then it stopped working
Follow the simple steps here....
1. Restart networking
sudo /etc/init.d/networking restart
2. Disable the "Support for Atheros 802.11 wireless LAN cards" on system/administration/Hardware Drivers, and reboot your box.
3. Restart
sudo reboot

That's it, Cheers! Still having problem follow the instructions here
Read More…

Wednesday, December 2, 2009

Hpricot scraping in ruby

by sandipransing 1 comments
Include gems/library required before getting started
require 'hpricot'
require 'net/http'
require 'rio'
# Pass website url to be scraped
url = "www.funonrails.com"

# Define filename to store file locally
file = "temp.html"
# Save page locally
rio(url) < rio (file)
# Open page through hpricot
doc = Hpricot(open(file))

Apply hpricot library to get right contents

doc.at("div.pageTitle")
doc/"div.pageTitle"
doc.search("div.entry")
doc//"div.pageTitle"
Hpricot API Reference click here
Read More…

Friday, November 27, 2009

Passing commandline parameter (arguments) to ruby file using optparser

by sandipransing 0 comments
Ruby file accepts from command prompt in the form of array.
Passing parameters
ruby input.rb TOI DH TimesNew
Accessing parameters
 # input.rb
 p ARGV
 # => ["TOI", "DH", "TimesNew"]
 p ARGV[0]
 # => "TOI"
 p ARGV[1]
 # => "DH"
Optparser : parses commandline options in more effective way using OptParser class. and we can access options as hashed parameters.

Passing parameters
ruby input.rb -P"The Times of India" --category"article"
Accessing parameters
 
 # input.rb
 require 'optparser'
 
 options = ARGV.getopts("P:", 'category')

 p options
 # => { 'P' => 'The Times of India', :category => 'article' }

 p options['P']
 # => "The Times of India"
Read More…

Thursday, November 26, 2009

How to get all associated models of rails model

by sandipransing 0 comments
I have Site Model and i wanted to find all associated models of Site model which are having belongs_to relationship. After doing lot headache, here is the solution i found


has_many models of Site Model
 Site.reflect_on_all_associations.map{|mac| mac.class_name if mac.macro==:has_many}.compact
=> ["Layout", "User", "SubmenuLink", "Snippet", "Asset"]

belongs_to model of Site Model
Site.reflect_on_all_associations.map{|mac| mac.class_name if mac.macro==:belongs_to}.compact
=> ["User", "Page", "User"]

To get all associations
Site.reflect_on_all_associations.map{|mac| mac.class_name}.compact
=> ["Layout", "User", "Page", "User", "SubmenuLink", "User", "Snippet", "Asset"]

Hari, U rocks !
Read More…

Tuesday, November 24, 2009

Cricket challenge flash game

by sandipransing 0 comments
Advanced cricket flash game





Read More…

Flash games

by sandipransing 0 comments
3rd worm game ----------------------
  Racing Game ----------------------
 
Read More…

Gravity Master Game Challenge

by sandipransing 0 comments
Collect all rotating circles with the black ball. You can move the ball by drawing shapes with mouse and using physics. The ways of completing a level is only limited by your imagination and line limit. Complete 15 levels to unlock level editor. I recommend to lower your mouse sesitivity. P.S. This is the first game I ever made

Read More…

Monday, November 23, 2009

Upgrading openoffice in ubuntu interpid

by sandipransing 0 comments
Follow simple steps defined in this post for smooth upgrade of openoffice in linux.

click here
Read More…

bundling gems in rails application

by sandipransing 0 comments
Gem Bundling is basically used to maintain all required gems at your application level. It downloads necessary gems and maintain it under "/vender/gems" directory. Its very easy to use gem bundle.
1. Insatll gemcutter gem ( Its gem hosting )
gem install gemcutter
2. Install bundler ( Its a tool that manages gem dependencies for your ruby application. )
gem install bundler
3. Start using
gem bundle
Read More…

Wednesday, November 18, 2009

Get hand over VI / VIM editor

by sandipransing 1 comments

Movements
b   previous word
w   next word
e        end of word
0/^      begining of line
$        end of line
G        end of file
1G/gg    begining of file
/pattern  search next
?pattern  search previous
n         repeat    search forword ( i.e next occurence )
N         repeat    search backword
:line     goto line specified

  *****Modes****
  i   insert mode
  r   replace mode
  s   delete character under cursor and eneter insert mode

  *****Delete******
  x    delete character under cursor
  dd   delete current line
  line dd delete number of lines specified

  ****copy********
  yy        copy current line
  pp        print copied contents
  line yy   copy number of lines specified

  *******visual******

  v     enter visual mode
  aw    highlight word
  as    highlight sentence
  ap    highlight paragraph
  ab    highlight block

  ******undo/redo******
  u       undo
  cntrl+r redo

  ******autocomplete****
  cntrl+x   enter completion mode
  cntrl+p   display autocomplete options

  ******uppercase/lowercase*****
  guu   lowercase line
  gUU   uppercase line

  *******Regx replace****

  range s/foo/bar/arg - replace foo with bar in ‘range’ with

  Values of 'range':
  %               whole file
  number          that particular line
  none            apply to current line only

  values of 'arg':
  none  apply to first occurrence
  g     global (all occurrences)

Select/Macros
  qchar      start recording macro storing it in register ‘char’
  q          end recording
  @char      replay the macro stored in ‘char’
  :1,10 norm! @char run the macro stored in ‘char’ over the 1-10 line range

Read More…

Tuesday, November 17, 2009

YAML file configuration in ruby & rails

by sandipransing 0 comments
While coding in ruby and rails, we often requires variables to be initialized that can be used across application. There are many ways to define configuration variables

1. Initialize variables inside environment file
  # This agencies can be used across application
  AGENCIES = ['TIMES NEWS NETWORK', 'AGENCIES', 'AFP', 'PTI']

  # Configuration for html nodes

  Article_title_tag = "h1.heading"
  Date_auth_agency_tag = "span[@class='byline']"
  Location_content_tag = "div[@class='Normal']"
2. Inside config/initializers/config.rb. Just make config.rb inside initializers and add variables to it.
  #config/initializers/config.rb
  # This agencies can be used across application
  AGENCIES = ['TIMES NEWS NETWORK', 'AGENCIES', 'AFP', 'PTI']

  # Configuration for html nodes
  Article_title_tag = "h1.heading"
  Date_auth_agency_tag = "span[@class='byline']"
  Location_content_tag = "div[@class='Normal']"
3. But most efficient way to organize variables is YML file.
# config/config.yml
the_times_of_india:
  article_title_tag: h1.heading
  date_auth_agency_tag: span[@class='byline']
  loc_content_tag: div[@class='Normal']
Accessing YML files
 # config/initializers/load_config.rb
APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")
=> true
>> APP_CONFIG
=> {"the_times_of_india"=>{"article_title_tag"=>"h1.heading", "loc_content_tag"=>"div[@class='Normal']", "date_auth_agency_tag"=>"span[@class='byline']"}}
>> APP_CONFIG[:the_times_of_india]
=> nil
>> APP_CONFIG['the_times_of_india']
=> {"article_title_tag"=>"h1.heading", "loc_content_tag"=>"div[@class='Normal']", "date_auth_agency_tag"=>"span[@class='byline']"}
>> APP_CONFIG['the_times_of_india']['article_title_tag']
=> "h1.heading"
Read More…

Sunday, November 15, 2009

pidgin install and update pidgin messenger on ubuntu interpid

by sandipransing 0 comments
Fresh pidgin Installation
 sudo apt-get update
 sudo apt-get install pidgin
Earlier versions of pidgin has problem in connecting yahoo messenger which is solved in newer versions.
In order to update old version of pidgin, simply follow instructions written below and you are done.
New version provides video and voice chat, also buddy icon improvements are added.

Add GPG key
 sudo apt-get update
 sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys A1F196A8
Goto System > Administration > Software Sources and select Third-Party Software tab and click ADD. And Simply Copy-Paste the following Repo
deb http://ppa.launchpad.net/pidgin-developers/ppa/ubuntu intrepid main 
deb-src http://ppa.launchpad.net/pidgin-developers/ppa/ubuntu intrepid main
Read More…

Friday, November 13, 2009

How to remove extra spaces in ruby strings

by sandipransing 0 comments
In ruby, one can write multiple codes to remove multiple blank spaces inside strings (sentenses)
 
"Write      your       string            here   ".squeeze.strip
"This     is my      input  string     ".gsub(/ +/, ' ')
"Write      your       string          here   ".split('  ').join(' ')
Read More…

Thursday, November 12, 2009

Manual active record db connection in ruby using mysql adapter

by sandipransing 2 comments
Below is ruby code to establish manual database connection.
require 'active_record' ActiveRecord::Base.establish_connection( :adapter => "mysql", :host => "localhost", :username => "root", :password => "abcd", :database => "funonrails" )
Snippet of database.yml file
common: &common adapter: mysql database: students_dev username: root password: host: localhost students_development: <<: *common database: students_dev students_production: <<: *common database: students
Load database configurations from yml file
dbconfig = YAML::load(File.open('database.yml')) ActiveRecord::Base.establish_connection( dbconfig[:students_development] )
Active Record Model & DB connection
class Student < ActiveRecord::Base establish_connection "students_production" set_table_name "student" set_primary_key "stud_number" end
Read More…

Tuesday, November 10, 2009

Writing rake task in rails with namespace, parameters

by sandipransing 0 comments
Rake tasks itself defines that “they are bunch of ruby code that performs some task.” Rake tasks are placed in lib/tasks directory of application and files have .rake extension. There are many lovable tasks defined in rails. read more Rake tasks are executed from console. Benefit of writing rake task are Testing of code Scheduled rake tasks ( backgroundRb and scheduled tasks using cron ) Simplifies code Lets, understand what is code inside rake tasks.


Simple greet rake task
 
# lib/tasks/welcome.rake
task :greet do
  puts “Hello !!”
end

## Execute task
rake greet


Adding description to rake task
 
# lib/tasks/welcome.rake
desc “This is new style of greet”
task :greet do
  puts “Hello !!”
end
## Execute task
rake greet

Adding namespace to rake tasks

It's nothing but prefix that takes while executing rake task. Benefit of adding namespace is to categories similar rake tasks.
 
# lib/tasks/welcome.rake
namespace :introduction do
desc “This is one style of introduction”
task :greet do
  puts “Hello !!”
end
desc “This is 2nd style of introduction”
task :hi do
  puts “Hi ”
end
end
## Execute task
rake introduction:greet
rake introduction:hi

Passing arguments to rake tasks
 
# lib/tasks/welcome.rake

namespace :introduction do
desc “This is one style of introduction”
task :greet do
  puts “Hello !!”
end

desc “This is 2nd style of introduction”
task :hi => :enviroment do
  puts “Hi #{ENV['name']}”
end
end
## Execute task
rake introduction:hi name=Raj
read more
Read More…

Understanding and creating radinat extensions

by sandipransing 0 comments
Understanding and creating radinat extensions To start with, first of all lets know what is radiant and why to use it ? Radiant is a open source content management system designed that serves cms needs for small organisations Creating new radint application
 radiant -d  mysql cms
    create
    create    CHANGELOG
    create    CONTRIBUTORS
    create    INSTALL
    create    LICENSE
    create    README
    create    config
    create    config/environments
    .....
Radiant supports extensions. It means one can add extra features to radiant based cms to add extra capabilities. Extension directory structure is almost similar to any standard rails application Radiant Extension Directory structure
       |-- app
              |-- controllers
              |-- helpers
              |-- models
              |-- views
       |-- db
              |-- migrate
              |-- seeds.rb
       |-- lib
              |-- spec
                 |-- controllers
                 |-- helpers
                 |-- models
                 |-- spec.opts
                 |-- spec_helper
                 |-- views
Creating radiant extension radiant has generators to create new radint extension script/generate extension ExtensionName Lets create session management extension for radint cms It will create directory structure for extension.
script/generate extension session_management
    create    vendor/extensions/session_management/app/controllers
    create    vendor/extensions/session_management/app/helpers
    create    vendor/extensions/session_management/app/models
    create    vendor/extensions/session_management/app/views
     create vendor/extensions/session_management/db/migrate
     create vendor/extensions/session_management/lib/tasks
     create vendor/extensions/session_management/README
     create vendor/extensions/session_management/session_management_extension.rb
     create
vendor/extensions/session_management/lib/tasks/session_management_extension_tasks.rake
     create vendor/extensions/session_management/spec/controllers
     create vendor/extensions/session_management/spec/models
     create vendor/extensions/session_management/spec/views
     create vendor/extensions/session_management/spec/helpers
     create vendor/extensions/session_management/features/support
     create vendor/extensions/session_management/features/step_definitions/admin
     create vendor/extensions/session_management/Rakefile
     create vendor/extensions/session_management/spec/spec_helper.rb
     create vendor/extensions/session_management/spec/spec.opts
     create vendor/extensions/session_management/cucumber.yml
     create vendor/extensions/session_management/features/support/env.rb
     create vendor/extensions/session_management/features/support/paths.rb
Edit session_management_extension.rb where extension version, description and website url can be added.
# require_dependency 'application_controller'
class SessionManagementExtension < Radiant::Extension
  version "1.0"
  description "Describe your extension here"
  url "http://yourwebsite.com/session_management"
  # define_routes do |map|
  # map.namespace :admin, :member => { :remove => :get } do |admin|
  #     admin.resources :session_management
  # end
  # end
  def activate
    # admin.tabs.add "Session Management", "/admin/session_management", :after =>
"Layouts", :visibility => [:all]
  end
  def deactivate
    # admin.tabs.remove "Session Management"
  end
In activate block, specify what are the library files , modules that needs to be activated while application starts. In my case, activate method looks like below..
  def activate
    # admin.tabs.add "Session Management", "/admin/session_management", :after =>
"Layouts", :visibility => [:all]
   ApplicationController.send(:include, SessionManagementExt::ApplicationControllerExt)
  end
Generating models and controllers.
 script/generate extension_model session_management session_info
session_id:string url:string ip:string
In above command first attribute is the extension name and next is model name and rest specifies attributes that needs to created. It will create
     exists   app/models/
     exists   spec/models/
     create   app/models/session_info.rb
     create   spec/models/session_info_spec.rb
     exists   db/migrate
     create   db/migrate/20091110075042_create_session_infos.rb
Generating controller
script/generate extension_controller session_management admin/session_managements
It will create an output
create app/controllers/admin
     create app/helpers/admin
     create app/views/admin/session_managements
     create spec/controllers/admin
     create spec/helpers/admin
     create spec/views/admin/session_managements
     create spec/controllers/admin/session_managements_controller_spec.rb
     create spec/helpers/admin/session_managements_helper_spec.rb
     create app/controllers/admin/session_managements_controller.rb
     create app/helpers/admin/session_managements_helper.rb
Modify session managements controller for displaying sesssion infos tracked. We need before filter for every request that will capture session, ip and page url so, we need to override behaviour of application controller to add before_filter We have already added ApplicationControllerExt in activate of extension.
   ApplicationController.send(:include, SessionManagementExt::ApplicationControllerExt)
Lets look into ApplicationControllerExt module.
module SessionManagementExt
  module ApplicationControllerExt
    def self.included(base)
     base.class_eval do
       before_filter :track_session
     end
    end
    def track_session
     #**"Hello from Session tracker !!!"**
     #TODO: location track
     # It can be delayed task
     #sudo gem install geoip_city -- --with-geoip-dir=/opt/GeoIP
     # require 'geoip_city'
     # g = GeoIPCity::Database.new('/opt/GeoIP/share/GeoIP/GeoLiteCity.dat')
     # res = g.look_up('201.231.22.125')
     # {:latitude=>-33.13330078125, :country_code3=>"ARG",
:longitude=>-64.3499984741211, :city=>"Río Cuarto", :country_name=>"Argentina",
:country_code=>"AR", :region=>"05"}
     SessionInfo.create( :ip => request.remote_ip, :page_url =>
"http://#{request.env["HTTP_HOST"]}#{request.request_uri}", :session_id =>
request.session.session_id )
    end
  end
end
That's all Creating rake task for extension module here is default genrated rake task for session management under vendor/extensions/session_management/lib/tasks/session_management_extension_tasks.rake It includes task to migrate database and update extension
namespace :radiant do
  namespace :extensions do
    namespace :session_management do
     desc "Runs the migration of the Session Management extension"
     task :migrate => :environment do
       require 'radiant/extension_migrator'
       if ENV["VERSION"]
         SessionManagementExtension.migrator.migrate(ENV["VERSION"].to_i)
       else
         SessionManagementExtension.migrator.migrate
       end
     end
     desc "Copies public assets of the Session Management to the instance public/ directory."
     task :update => :environment do
       is_svn_or_dir = proc {|path| path =~ /\.svn/ || File.directory?(path) }
       puts "Copying assets from SessionManagementExtension"
       Dir[SessionManagementExtension.root + "/public/**/*"].reject(&is_svn_or_dir).each do
|file|
         path = file.sub(SessionManagementExtension.root, '')
         directory = File.dirname(path)
         mkdir_p RAILS_ROOT + directory, :verbose => false
         cp file, RAILS_ROOT + path, :verbose => false
       end
     end
    end
  end
end
Add as many custom tasks needed inside this file without changing default tasks. Migrate all radiant extensions
rake db:migrate:extensions
Read More…

Friday, November 6, 2009

Linux commands for remote access, compress, decompress

by sandipransing 0 comments


Remote Login
============
ssh client is a program for logging into remote machine and execute commands.

ssh [-l login_name ] hostname | user@hostname [command ]

other options

ssh [-afgknqstvxACNTX1246 ] [-b bind_address ] [-c cipher_spec ] 
[-e escape_char ] [-i identity_file ] [-l login_name ] [-m mac_spec ] 
[-o option ] [-p port ] [-F configfile ] [-L port host hostport ] 
[-R port host hostport ] [-D port ] hostname | user@hostname [command ]

One can use putty for remote login through windows machine

Remote Copy
============
scp - secure copy (remote file copy program) that copies file between computers over network

scp source[ source file path] destination[user@funonrails.com:/home]

Other options

[-F ssh_config ] [-S program ] [-P port ] [-c cipher ] [-i identity_file ] 
[-o ssh_option ] [[user@ ] host1 : file1 ] [... ] [[user@ ] host2 : file2 ]

One can use pscp.exe for remote copy from windows machine

Compress
============
tar - is a package that allows you to compress direcory or file

tar czfv Test.tar.tgz Test/

Decompress
============
gzip - is a package that allows to extract compressed file/directories.

gzip -dc target.tar.tgz | tar xf -




Read More…

Thursday, November 5, 2009

Variables initialization, assignments and swapping in ruby

by sandipransing 0 comments
Just a single line variable swap in ruby
x,y=y,x
Example:

irb>> x = "Fun"
=> "Fun"
irb>> y = "Rails"
=> "Rails"
irb>> x,y = y,x
=> ["Rails", "Fun"]
irb>> p x
"Rails"
=> nil
>> p y
"Fun"
Variable assignments in Ruby
we can do multiple assignments in a single line.

irb>> a,b,c,d = 1,2,3,4
=> [1, 2, 3, 4]


here is interpretation of above line

irb>> p "a => #{a} b => #{b} c => #{c} d => #{d}"
"a => 1 b => 2 c => 3 d => 4"

Multiple assignments in ruby


a = b = c = d = 12

This means a,b,c,d variables has value 12
Read More…

Tuesday, November 3, 2009

Ruby On Rails Developers in India

by sandipransing 1 comments
Hello ROR lovers,

I wanted to list down ruby on rails developers in india. I would glad to see your name in this list. Lets, see how much rails hobbies are there in india.

Thanks,
Sandip

List goes here..................

Name: Sandip Ransing
ROR Experience: 2.1 yrs
Overall: 2.8+ yrs
Location: Pune
Company: Josh Software Private Limited.
Name: Amit Yadav
Experience: 2.5 yrs
Overall: 5.8 yrs
Location: Pune
Company: Globallogic
Name: Haribhau Ingale
ROR Experience: 4 yrs
Overall: 5+ yrs
location: Pune
Company: Persistent Systems Ltd.
Name: ABHISHEK V. AMBAVANE
ROR Experience: WITHOUT ADOBE FLEX AROUND 6 MONTHS WITH FLEX,AIR IS AROUND 1 YR.
Overall: 2.8 YRS.
Location: PUNE
Company: BETTERLABS
Name: Sunny Bogawat
ROR Experience: 1.5 YR.
Location: PUNE
Company: Neova solutions
Name: Kiran Chaudhari
ROR Experience: 1.8 YR.
Location: PUNE
Company: Josh Software Private Limited.
Name: Swati Verma
ROR Experience: 1.2 YR.
Location: Jaipur
Company: Rising Sun Technologies
Name: Satish Talim
Ruby Experience: 4 yrs
Overall: 32+ yrs
Location: Pune
Company: RubyLearning portals
Name: Arun Agrawal
Ruby Experience: 3 yrs
Overall: 3+ yrs
Location: Jaipur
Company: Rising Sun(Jaipur)
Name: Piyush Gajjariya
ROR Experience: 2.5 Years
Location: Bangalore
Company: Pramata Knowledge Solutions
Name: Puneet Pandey
ROR Experience: 2 yrs
Overall: 3 Yrs
Location: Hyderabad
Company: Zibika Infotech Pvt. Ltd
Name: Uma Mahesh Varma
ROR Experience: 2 yrs
Overall: 3 Yrs
Location: Kakinada
Company: Nyros Technologies, Kakinada
Name: Mohammed Imran Ahmed
ROR Experience: 1 year
Overall: 2 year 3months Yrs
Location: Hyderabad
Company: Prithvi Information Solutions, Hyd
Name: Amit Kulkarni
Title: QA,Rspec Testing in ROR
Overall: 1.5 yrs
Location: Pune
Company: Josh Software Private Limited.
I am a Software Engineer with more than three years of experience in Information Technology Industry. I worked on different Business Intelligence / Data Warehousing Projects in my experience.
I am a C, C++ & UNIX enthu. I recently learnt ruby & looking forward to work in this.
Thanks,
Pankaj Sisodiya
Name: M B Chowdari
ROR Experience: 1.3 yrs
Overall: 2.3 Yrs
Location: Kakinada
Company: Nyros Technologies, Kakinada
Now your turn
Read More…

Tuesday, October 27, 2009

10 steps to get start with MySpace Ruby SDK

by sandipransing 0 comments
Follow 10 simple steps in order to use myspace sdk api

1. Remove all your previous gems installed
+ gem uninstall myspace

2. Checkout sample source code

svn checkout http://myspaceid-ruby-sdk.googlecode.com/svn/trunk/ myspacesdk

3. cd myspacesdk/samples/rails/sample
4. Modify config/database.yml accordingly

development:
adapter: mysql
database: sample_development
password: abcd
pool: 5
timeout: 5000

5. Download http://myspaceid-ruby-sdk.googlecode.com/files/myspaceid-sdk-0.1.11.gem
6. gem install --local ~/Desktop/myspaceid-sdk-0.1.11.gem i.e.PATH_TO_GEM
7. Above command supposed to give you following error otherwise skip to step 10

ERROR:  Error installing /home/sandip/Desktop/myspaceid-sdk-0.1.11.gem:
myspaceid-sdk requires ruby-openid (>= 0, runtime)

8. gem install ruby-openid go to step 6
9. ruby script/server
10. Browse http://localhost:3000/
Read More…

Hello

by sandipransing 0 comments
Hello from Fun On Rails www.funonrails.com
Read More…

Monday, October 26, 2009

Find processor (cpu) information on linux

by sandipransing 0 comments
Here is the command

cat /proc/cpuinfo


Example use on my ubuntu machine, It shows me.



cat /proc/cpuinfo
processor : 0
vendor_id : GenuineIntel
cpu family : 6
model : 15
model name : Intel(R) Pentium(R) Dual CPU T2330 @ 1.60GHz
stepping : 13
cpu MHz : 800.000
cache size : 1024 KB
physical id : 0
siblings : 2
core id : 0
cpu cores : 2
apicid : 0
initial apicid : 0
fdiv_bug : no
hlt_bug : no
f00f_bug : no
coma_bug : no
fpu : yes
fpu_exception : yes
cpuid level : 10
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx lm constant_tsc arch_perfmon pebs bts pni monitor ds_cpl est tm2 ssse3 cx16 xtpr lahf_lm
bogomips : 3191.95
clflush size : 64
power management:

processor : 1
vendor_id : GenuineIntel
cpu family : 6
model : 15
model name : Intel(R) Pentium(R) Dual CPU T2330 @ 1.60GHz
stepping : 13
cpu MHz : 800.000
cache size : 1024 KB
physical id : 0
siblings : 2
core id : 1
cpu cores : 2
apicid : 1
initial apicid : 1
fdiv_bug : no
hlt_bug : no
f00f_bug : no
coma_bug : no
fpu : yes
fpu_exception : yes
cpuid level : 10
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx lm constant_tsc arch_perfmon pebs bts pni monitor ds_cpl est tm2 ssse3 cx16 xtpr lahf_lm
bogomips : 3192.03
clflush size : 64
power management:

Read More…

How to find OS X version on linux machine

by sandipransing 0 comments
Here is the command which will give you OS name with version along with other detail information.

cat /etc/*release*


Example: On my ubutnu machine, It shows me.



cat /etc/*release*
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=8.10
DISTRIB_CODENAME=intrepid
DISTRIB_DESCRIPTION="Ubuntu 8.10"
Read More…

Wednesday, October 21, 2009

How to map irregular database tables with rails models

by sandipransing 2 comments
Rails specifies conventions while creating models, controllers, migrations ( database tables ).

Conventions for creating database tables
1. Table name should be plural
2. id field should be primary_key for table.
3. foreign_key should be like _id i.e. post_id, site_id

Conventions for creating models & Controllers
1. Model name should be singular
2. controller name should be plural.
Although rails has standard defined, In some cases it becomes quite necessary to map irregular

1. Table mapping
class Review < ActiveRecord::Base # Here comments is name of database table set_table_name :comments end
2. Set primary key ( other than rails standar 'id' primary_key )
class Review < ActiveRecord::Base # It assumes "reviews" as table in database # Below line indicates reviews table contains column_name "reviewId" which is a primary_key set_primary_key :reviewId end
3. Foreign key association
class Review < ActiveRecord::Base # Below line indicates reviews table contains column_name 'RatingId' which is foreign_key to primary_key # of 'ratings' table. # It can be applied to any associan type [ has_one, has_many, belongs_to, has_many_through ] belongs_to :rating, :class_name => "SiteUser", :foreign_key => "RatingId" end
4. Model association ( non-standard model name )
class Review < ActiveRecord::Base # Below line indicates reviews table contains column_name 'UserId' which is foreign_key to primary_key # of model with class_name 'SiteUser' belongs_to :user, :class_name => 'SiteUser', :foreign_key: => 'UserId' end
Read More…

Wednesday, October 14, 2009

Getting wireless working on ubuntu machine

by sandipransing 1 comments
Please follow following steps blindly to get wireless working on ubuntu machine.

Here are the steps...

On a fresh clean Ubuntu machine:
1. Disable the "Support for Atheros 802.11 wireless LAN cards" on Hardware Drivers, and reboot your box.

2. In a terminal:

2.1 Updates all package lists
# sudo apt-get update

2.2 Update driver.
# sudo apt-get install linux-backports-modules-intrepid-generic


3. Reboot.

Thanks to Gautam, directing me correct way :)
Here are the steps
Read More…

Monday, October 12, 2009

Feedzirra installtion on ubuntu interpid

by sandipransing 0 comments
Feedzirra is a feed library that is designed to get and update many feeds as quickly as possible. This includes using libcurl-multi through the taf2-curb gem for faster http gets, and libxml through nokogiri and sax-machine for faster parsing.
sudo apt-get install libcurl3 libxml2 libxml2-dev libxslt1-dev


sudo gem install pauldix-feedzirra

Read More…

Wednesday, October 7, 2009

Converting dos(windows) files to unix files

by sandipransing 0 comments

While using windows we get ^M characters in files that will get displayed when you open files on unix machines.


To remove such ^M characters,


Install dos2unix package using


sudo apt-get install sysutils


Convert individual file


dos2unix file_path


Run following command to convert recursively all the files inside directory.



find . -type f -exec dos2unix {} \;




sudo apt-get install sysutils

Read More…

Thursday, October 1, 2009

How to submit sitemap to search engines

by sandipransing 6 comments

There are many ways that can be used to submit sitemap to search engines.

Lets discuss approaches

1. Put sitemap.xml in public folder and you are done.
    Crawlers will find it through url
    http://yourdomain.com/sitemap.xml

2. There are many online sites which generates sitemaps for you.
    like http://www.xml-sitemaps.com/

3. Open following urls in browser. Be sure to add xml sitemap path for your site.

a. Google submit
    http://www.google.com/webmasters/tools/ping?sitemap=XML_SITEMAP_PATH

b. Yahoo Submit
    http://search.yahooapis.com/SiteExplorerService/V1/ping?sitemap=XML_SITEMAP_PATH

c. Ask Submit
    http://submissions.ask.com/ping?sitemap=XML_SITEMAP_PATH

d. Webmaster submit
    http://webmaster.live.com/ping.aspx?siteMap=XML_SITEMAP_PATH

5. Best practices in rails to submit sitemap is scheduled task (cron job).
    Write a rake task that will generate sitemap in rails public folder and
    will submit sitemap.xml file to search engines. ( as mentioned above.)

Got easy :)
Read More…

Wednesday, September 30, 2009

--no-ri --no-rdoc for ruby gem installation

by sandipransing 1 comments
One can install gem without rdoc using

gem install GEM_NAME --no-ri --no-rdoc


Skip ri rdoc for all gem installation as i haven't seen anyone using it.

Edit gemrc file
Add following line to it
vi ~/.gemrc
:gem: --no-ri --no-rdoc


Here is my ~/.gemrc file
---
:verbose: true
gem: --no-ri --no-rdoc
:update_sources: true
:sources:
- http://gems.rubyforge.org
- http://gems.github.com
:backtrace: false
:bulk_threshold: 1000
:benchmark: false


That's it !
Read More…

Managing multiple ruby versions and rails versions with rvm

by sandipransing 2 comments
While working with many projects that uses different ruby versions and rails versions, one big problem arises that how do we manage all this ?

We know that managing multiple rails versions wont be problem at all.
but what about ruby versions, How one can manage multiple ruby versions. also while upgrading or degrading ruby version, we need to install all gems again including rails.
i know this is a big pain :(
How we can overcome this headache. meantime there must be some incompatibilities between two different ruby and rails versions.

Yesterday, i did some research and came to know that...

+ ruby 1.8.7 and rails 2.3.3 got quite stability and effectively. we can use it in next developments.
+ Also, after installing ruby 1.9.1 and dependent gems for my project,
and wondering that there are many incompatibilities while installing new gems with ruby 1.9.1

Some of the gems are mysql, ferret, acts_as_ferret, erubies, etc.

Today, while google, i found rvm gem and that seems very nice to manage multiple ruby versions.


Here are some steps explaining how to use it.

# Install rvm gem to manage multiple ruby version
# pre-requisite is that we already have ruby and rubygems installation
1. sudo gem install rvm

# Install rvm for a particular user
# It will also show how to use gem
2. rvm-install

3. Open new shell

# Show all ruby, jruby installations
4. rvm list

# Install ruby
# specify ruby version
5. rvm install RUBY_VERSION_TO_BE_INSTALLED
(rvm install 1.9.1)

# Install jruby
# By default it will install jruby-1.3.1
6. rvm install jruby

# Specify which ruby version to use ?
# Note: Be sure that ruby version is installed
7. rvm use RUBY_VERSION_TO_USE
(rvm use 1.9.1)

#. Default i.e. version before rvm gem installation
8. rvm use default

Sounds, cool :)
Read More…

Tuesday, September 29, 2009

jruby rails installation on ubuntu interpid

by sandipransing 1 comments
# install mysql if you dont have already installed
sudo apt-get install mysql-server mysql-client libhtml-template-perl mailx dbishell libcompress-zlib-perl mysql-doc-5.0 tinyca

# install ant and jdk
sudo apt-get install ant sun-java6-jdk

# install jruby
mkdir software
cd software
wget http://dist.codehaus.org/jruby/jruby-bin-1.1.5.tar.gz
tar xvfz jruby-bin-1.1.5.tar.gz
ln -s jruby-1.1.5 jruby
export PATH=$PATH:$HOME/software/jruby/bin

# install the version of rails wanted by jruby
jruby -S gem install jruby-openssl
jruby -S gem install rails

# list your gems
jruby -S gem list

# install the gems needed for db
jruby -S gem install activerecord-jdbc-adapter activerecord-jdbcmysql-adapter

# generate some code
cd ~/scripts/ruby
jruby -S rails wherehaveyoubeen -d mysql
cd wherehaveyoubeen
jruby script/generate controller states index

# configure access to the database server
vi config/database.yml

#development:
# adapter: jdbcmysql <- very important!
# encoding: utf8
# database: test_development
# username: root
# password: database
# socket: /var/run/mysqld/mysqld.sock

# generate the db
jruby -S rake db:create:all
jruby -S rake db:migrate


# edit your app
sudo apt-get install emacs ruby-elisp irb1.8 emacs22-el
emacs -bg black -fg wheat app/views/states/index.html.erb

# uncomment the secret in app/controllers/application.rb
vi app/controllers/application.rb

# run your app
jruby script/server
Read More…

upgrading rails version

by sandipransing 0 comments
Here are the simple steps to be followed while upgrading rails version to use.

# Install rails version
1. gem install rails -v
== gem install rails 2.3.3

# Upgrade environment.rb for new version
2. RAILS_GEM_VERSION = '' unless defined? RAILS_GEM_VERSION
== RAILS_GEM_VERSION = '2.3.3' unless defined? RAILS_GEM_VERSION

# Upgrade necessary files for the new version
3. rake rails:upadte

# Start server
4. /script/server


Thats, it !
Read More…

Installing ruby 1.9.1

by sandipransing 0 comments
installing ruby 1.9.1 is very easy .......
follow simple steps

wget ftp://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.1-p0.tar.gz

tar -xvf ruby-1.9.1-p0.tar.gz

cd ruby-1.9.1-p0
./configure

make
make test
sudo make install


Thats, it !
Read More…

Friday, September 25, 2009

Migrating project from rails 2.1.0 to edge rails 2.3.3

by sandipransing 1 comments
I wanted to migrate my project from rails 2.1.0 to rails 2.3.3
so, i performed following steps, but it shows me memcached-client error.

vi config/environment.rb

# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.3' unless defined? RAILS_GEM_VERSION


ruby script/server

It shows me error
`install_memcached': 'memcache-client' client requested but not installed. Try 'sudo gem install memcache-client'. (Interlock::ConfigurationError)

so, i installed memcache-client gem

gem install memcache-client

but still i am showing same error, any ideas ??
Read More…

Monday, September 21, 2009

Thank You

by sandipransing 0 comments
Thanks for your valuable feedback!
Read More…

Contact Me

by sandipransing 0 comments
I would be thankful to you for any suggestions or advice you give for the improvement of this blog !

Your Name
Your Email Address
Website/Blog
Subject
Message
   

Read More…

Monday, September 14, 2009

Watch live India vs Srilanka cricket

by sandipransing 0 comments
http://watch-online-cricket.blogspot.com/2009/01/watch-india-vs-srilanka-cricket-online.html
Read More…

Wednesday, September 9, 2009

4 steps to install nginx with passenger

by sandipransing 2 comments
Install passenger program that will run your rails application
1. sudo gem install passenger
Install nginx server with passenger enabled
2. passenger-install-nginx-module

it will open apt, click "Enter" to contine
then select option 1 for default install
then it will ask
Where do you want to install Nginx to?

Please specify a prefix directory [/opt/nginx]:
press enter

then copy following block

server {
listen 80;
server_name www.yourhost.com;
root /somewhere/public;   # <--- be sure to point to 'public'!
passenger_enabled on;
}


Make nginx Configuration
3. vi /opt/nginx/conf/nginx.conf
Make passenger_root and passenger_ruby path to configuration


http {
passenger_root /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.4;
passenger_ruby /usr/local/bin/ruby;


then add server configuration block inside http block
http{
...
server {
listen 80;
server_name www.yourhost.com; //Make sure this dns entry inside /etc/hosts
root /carsonline/public;   # <--- be sure to point to 'public'! //here carsonline is RAILS_ROOT
passenger_enabled on;
}


Thats, all

4. Launch Server

/opt/nginx/sbin/nginx
Read More…

How do i generate SEO sitemap in rails ?

by sandipransing 6 comments
What is sitemap ?

Sitemap is nothing but a .xml file containing urls available on your site

It contains URL, last modified date, frequency of content change and priority ( between 0..1 )

Why we need sitemap ?

We can submit sitemap file to search engine. It will help them in analysing what urls on your site are available for crawling.

What is xml pattern ?
   <?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

<url>
<loc>http://www.example.com/</loc>
<lastmod>2005-01-01</lastmod>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
...
...
</urlset>

What will be the path for sitemap ?

"www.example.com/sitemap.xml"

Are we going to generate sitemap manually ?

No... there is mephisto sitemap plugin.We can use it.

script/plugin install http://svn.appelsiini.net/svn/rails/plugins/mephisto_sitemap/

Am i needed to generate to sitemap for each request ?

No ...........we can generate it in background task daily basis.

How it will be accessed for request to sitemap ?

we can define path to local file in routes.

map.connect "sitemap.xml", :controller => :sitemap

Class SitemapController

def index

render "some local file path"

end

....

Here are the reference links

http://www.fortytwo.gr/blog/19/Generating-Sitemaps-With-Rails

http://www.bestechvideos.com/2008/07/04/ruby-plus-71-how-to-create-a-seo-sitemap-for-rails-apps
Read More…

Friday, September 4, 2009

Social Media Overview

by sandipransing 1 comments
[gigya width="425" height="355" src="http://static.slideshare.net/swf/ssplayer2.swf?doc=socialmediaoverview-mar09-090325125549-phpapp01&stripped_title=social-media-overview-1197231" quality="high" wmode="tranparent" ]
Read More…

Wednesday, September 2, 2009

What is new in edge rails 2.3.3 ?

by sandipransing 1 comments
Rails community has released rails 2.3.3 recently with major upgrades and several bug fixes added.

On the other side, Rails 3 ( i.e. merge of rails and merb framework ) is supposed to be officially get released in this May.

Lets see what are the notable features added in rails 2.3.3

1. Rack

What is this rack ?

Abstraction built on the top of rails framework

What it does ?
It provides minimal interface between webservers supporting ruby ( like  apache-mongrel, nginx-passenger ) and rails framework.
Gives access to middleware goodness
i.e. wrapping HTML requests and response in simple way
unifies and distills the API for web servers, web frameworks, and software in between

read more ...

2. Metal
It is a subset of rack middleware specially designed to integrate with rails    application.

Why to use it ?
Whenever you need achieve raw speed for certain requests by skipping action controller stack.
read more ...

3. Engines
It was a plugin that got merged in rails core.
It is used for sharing controllers, models and views seamlessly from within a plugin to your rails application.
read more ...

4. Templates
These are the ruby files which describes which gems, plugins and initiliazers  has to be added while creating new rails project.
read more ...

5. Nested Forms
Earlier nested forms for has_one and has_many associations wasn't
there in rails.
this release added nested forms complex associations in models.
read more ... also see ...

One of good rails architecture diagram found while google


[caption id="" align="alignnone" width="460" caption="Rails 2.3 architecture diagram"]Rails 2.3 architecture diagram[/caption]

Edge rails Installation
gem install rails --source http://gems.rubyonrails.org

Thanks to rails community  for bringing this things in rails core.
Cheers, now rails is getting its way !
Read More…

Monday, August 17, 2009

Ruby On Rails Search Engine Optimization (SEO)

by sandipransing 0 comments
Search Engines ( like google, yahoo ) mainly uses crawlers for returning results.

Crawler is the program which searches world wide web ( www ) and returns ranked pages.

Lets see what are the search engine optimization (SEO) techniques we can adopt so that your rails
website pages will appear in search results.

1. Title Of Page

2. Meta tags

3. Page URL

4. Page Contents ( this includes anchors to other pages, headers, image titles and alt texts when image not found then normal texts )

We can easily skip some pages from search by mentioning them in robots.txt which is by default should be in application root.

And Ofcourse, we can manage all this in rails very easily..

How ????

We can have in rails

1. Dynamic page titles,

2. Meta tags and

3. Sexy perma URLs in rails

4. Also, we can define some standard on page content development.

...got Easy ......, Cheers !

$@ndip
Read More…

Easy sphinx install on ubuntu interpid

by sandipransing 1 comments
sudo apt-get install libmysqlclient15-dev

wget http://sphinxsearch.com/downloads/sphinx-0.9.8-rc2.tar.gz
tar xvf sphinx-0.9.8-rc2.tar.gz && rm sphinx-0.9.8-rc2.tar.gz
cd sphinx-0.9.8-rc2
./configure
make
sudo make install
Read More…

Friday, May 22, 2009

Intresting String inflections in rails

by sandipransing 1 comments
* camelcase
* camelize
* classify
* constantize
* dasherize
* demodulize
* foreign_key
* humanize
* parameterize
* pluralize
* singularize
* tableize
* titlecase
* titleize
* underscore


camelcase(first_letter = :upper)

Alias for camelize
camelize(first_letter = :upper)

By default, camelize converts strings to UpperCamelCase. If the argument to camelize is set to :lower then camelize produces lowerCamelCase.

camelize will also convert ’/’ to ’::’ which is useful for converting paths to namespaces.

"active_record".camelize # => "ActiveRecord"
"active_record".camelize(:lower) # => "activeRecord"
"active_record/errors".camelize # => "ActiveRecord::Errors"
"active_record/errors".camelize(:lower) # => "activeRecord::Errors"

This method is also aliased as camelcase

classify()

Create a class name from a plural table name like Rails does for table names to models. Note that this returns a string and not a class. (To convert to an actual class follow classify with constantize.)

"egg_and_hams".classify # => "EggAndHam"
"posts".classify # => "Post"

Singular names are not handled correctly.

"business".classify # => "Busines"

constantize()

constantize tries to find a declared constant with the name specified in the string. It raises a NameError when the name is not in CamelCase or is not initialized.

Examples

"Module".constantize # => Module
"Class".constantize # => Class

dasherize()

Replaces underscores with dashes in the string.

"puni_puni" # => "puni-puni"

demodulize()

Removes the module part from the constant expression in the string.

"ActiveRecord::CoreExtensions::String::Inflections".demodulize # => "Inflections"
"Inflections".demodulize # => "Inflections"


foreign_key(separate_class_name_and_id_with_underscore = true)

Creates a foreign key name from a class name. separate_class_name_and_id_with_underscore sets whether the method should put ‘_’ between the name and ‘id’.

Examples

"Message".foreign_key # => "message_id"
"Message".foreign_key(false) # => "messageid"
"Admin::Post".foreign_key # => "post_id"

humanize()

Capitalizes the first word, turns underscores into spaces, and strips ‘_id’. Like titleize, this is meant for creating pretty output.

"employee_salary" # => "Employee salary"
"author_id" # => "Author"

parameterize()

Replaces special characters in a string so that it may be used as part of a ‘pretty’ URL.
Examples

class Person
def to_param
"#{id}-#{name.parameterize}"
end
end

@person = Person.find(1)
# => #


# => Donald E. Knuth

pluralize()

Returns the plural form of the word in the string.

"post".pluralize # => "posts"
"octopus".pluralize # => "octopi"
"sheep".pluralize # => "sheep"
"words".pluralize # => "words"
"the blue mailman".pluralize # => "the blue mailmen"
"CamelOctopus".pluralize # => "CamelOctopi"

singularize()

The reverse of pluralize, returns the singular form of a word in a string.

"posts".singularize # => "post"
"octopi".singularize # => "octopus"
"sheep".singularize # => "sheep"
"word".singularize # => "word"
"the blue mailmen".singularize # => "the blue mailman"
"CamelOctopi".singularize # => "CamelOctopus"

tableize()

Creates the name of a table like Rails does for models to table names. This method uses the pluralize method on the last word in the string.

"RawScaledScorer".tableize # => "raw_scaled_scorers"
"egg_and_ham".tableize # => "egg_and_hams"
"fancyCategory".tableize # => "fancy_categories"

titlecase()

Alias for titleize
titleize()

Capitalizes all the words and replaces some characters in the string to create a nicer looking title. titleize is meant for creating pretty output. It is not used in the Rails internals.

titleize is also aliased as titlecase.

"man from the boondocks".titleize # => "Man From The Boondocks"
"x-men: the last stand".titleize # => "X Men: The Last Stand"

This method is also aliased as titlecase

underscore()

The reverse of camelize. Makes an underscored, lowercase form from the expression in the string.

underscore will also change ’::’ to ’/’ to convert namespaces to paths.

"ActiveRecord".underscore # => "active_record"
"ActiveRecord::Errors".underscore # => active_record/errors
Read More…

Render partial or view from another controller

by sandipransing 0 comments
To render view from another controller

# In rail 2.3
render "controller/action"

# In rails 2.2 or below
render :template => 'controller/action'

To render partial from another controller's views folder

render :partial => "controller/partial"

Cheers !
Sandip
Read More…

vi / vim Shortcuts

by sandipransing 2 comments
Open file
vi filename
As i am newb on linux macine, i dont know vi shortcuts.
so, i am listing down shortcuts which i am getting familier. :)

Insert in file
i

Exit file
q

forced exit
q!

save file
wq

forced save
wq!

Copy no of lines
yy

Paste copied lines
pp

Undo changes
uu

Delete lines
dd

To search and replace string in vi
:%s/search_string/replacement_string/g

To find particular word in file
?string1

If you have any quick list. please, let me know
Read More…

Wednesday, May 13, 2009

Working with multiple ruby versions on same server

by sandipransing 1 comments
click for original postNice post by Michael Greenly

I recently changed how I'm handling multiple simultaneous Ruby installations and I'd like to share.

What I needed was to make it convenient to switch between the system provided packages and specific, from source, installations. After some experiments I decided to use 'update-alternatives' to do it.

Here's a quick walk through...

First I removed all of my Ruby and RubyGem environment variables, they're not needed.

Then I installed Ubuntu's default Ruby packages via apt-get.

$ sudo apt-get install ruby irb ri rdoc libruby-extras rubygems ruby1.8-dev


Next I downloaded and installed alternate versions of Ruby from source. In this example I'm going to use two additional versions; the newest stable release and the newest development release.

$ cd /tmp
$ wget -c ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.7-p71.tar.gz
$ tar -xvzf ruby-1.8.7-p71.tar.gz
$ cd ruby-1.8.7-p71
$ ./configure --prefix=/opt/ruby-1.8.7-p71
$ make
$ sudo make install
$ wget -c ftp://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.0-3.tar.gz
$ tar -xvzf ruby-1.9.0-3.tar.gz
$ ./configure --prefix=/opt/ruby-ruby-1.9.0-3
$ make
$ sudo make install


At this point I have three versions of Ruby installed and each can be accessed through it's full path.

$ /usr/bin/ruby --version
# ruby 1.8.6 (2007-09-24 patchlevel 111) [i486-linux]
$ /opt/ruby-1.8.7-p71/bin/ruby --version
# ruby 1.8.7 (2008-08-08 patchlevel 71) [i686-linux]
$ /opt/ruby-1.9.0-r18217/bin/ruby --version
# ruby 1.9.0 (2008-07-25 revision 18217) [i686-linux]


You'll also notice that the default installation is the one provided by Ubuntu.

$ ruby --version
# ruby 1.8.6 (2007-09-24 patchlevel 111) [i486-linux]


Next we'll use 'update-alternatives' to make it a bit easier to switch between them. You could do this on the command line but it becomes a fairly long nasty command so I found it easier to write a quick shell script and run it. The script:

update-alternatives --install \
/usr/local/bin/ruby ruby /usr/bin/ruby 100 \
--slave /usr/local/bin/erb erb /usr/bin/erb \
--slave /usr/local/bin/gem gem /usr/bin/gem \
--slave /usr/local/bin/irb irb /usr/bin/irb \
--slave /usr/local/bin/rdoc rdoc /usr/bin/rdoc \
--slave /usr/local/bin/ri ri /usr/bin/ri \
--slave /usr/local/bin/testrb testrb /usr/bin/testrb

update-alternatives --install \
/usr/local/bin/ruby ruby /opt/ruby-1.8.7-p71/bin/ruby 50 \
--slave /usr/local/bin/erb erb /opt/ruby-1.8.7-p71/bin/erb \
--slave /usr/local/bin/gem gem /opt/ruby-1.8.7-p71/bin/gem \
--slave /usr/local/bin/irb irb /opt/ruby-1.8.7-p71/bin/irb \
--slave /usr/local/bin/rdoc rdoc /opt/ruby-1.8.7-p71/bin/rdoc \
--slave /usr/local/bin/ri ri /opt/ruby-1.8.7-p71/bin/ri \
--slave /usr/local/bin/testrb testrb /opt/ruby-1.8.7-p71/bin/testrb

update-alternatives --install \
/usr/local/bin/ruby ruby /opt/ruby-1.9.0-r18217/bin/ruby 25 \
--slave /usr/local/bin/erb erb /opt/ruby-1.9.0-r18217/bin/erb \
--slave /usr/local/bin/gem gem /opt/ruby-1.9.0-r18217/bin/gem \
--slave /usr/local/bin/irb irb /opt/ruby-1.9.0-r18217//bin/irb \
--slave /usr/local/bin/rdoc rdoc /opt/ruby-1.9.0-r18217/bin/rdoc \
--slave /usr/local/bin/ri ri /opt/ruby-1.9.0-r18217/bin/ri \
--slave /usr/local/bin/testrb testrb /opt/ruby-1.9.0-r18217/bin/testrb


What that does is create a group of applications under the generic name Ruby. In addition each application has several slave applications tied to it; erb, irb, etc... In defining each application we specify what symbolic link it will be accessed through and where the application is actually installed. In my case Ubuntu installed Ruby in /usr/bin and the source installed versions are in /opt. All of the installations will be accessed through the generic name Ruby and will have there symbolic links created in /usr/local/bin. I choose /usr/local/bin because it supercedes /usr/bin in the default path.

Before moving on make sure that 'update-alternatives' sees all of our Ruby installations:

$ update-alternatives --list ruby
# /opt/ruby-1.9.0-r18217/bin/ruby
# /opt/ruby-1.8.7-p71/bin/ruby
# /usr/bin/ruby


Now switching between them is as easy as running the 'update-alternatives' command and selecting the number of the installation you'd like to use. Example:

$ sudo update-alternatives --config ruby


It's important to keep in mind that each installation is separate. So for example if you install RubyGems while using /usr/bin/ruby it will not be available to /opt/ruby-1.9.0-r18217/bin/ruby, or /opt/ruby-1.8.7-p71/bin/ruby, etc....

While it's probably possible to use a shared repository for RubyGems across multiple installations I haven't tried it and instead have choosen to use multiple separate RubyGem installs, one for each Ruby installation.

Also RubyGem's bindir will most likely not be in your path. To get around this I created a short script called 'gemexec' in /usr/local/bin

#!/usr/bin/env ruby

require 'rubygems'

if ARGV.size > 1
exec "#{Gem.bindir}/#{ARGV.shift}",ARGV.join(" ")
else
exec "#{Gem.bindir}/#{ARGV.shift}"
end


This script uses the RubyGems installation of the currently selected Ruby to determine where the executable gem should be found, then runs it with any additional command line arguments provided. example:

$ gemexec rake --version
# rake, version 0.8.1


With all that in place the only thing to watch out for is other peoples scripts that hardcode the shebang line with something like "#!/usr/bin/ruby". What I do myself, and prefer in general, is to use "#!/usr/bin/env ruby".
Read More…

Ruby 1.8.7 and rails installation on ubuntu interpid

by sandipransing 1 comments
Execute following commands in order to install ruby and rails.

sudo apt-get install build-essential

Below command will install all necessary packages.
if you dont want any remove it from command.

sudo apt-get install ruby ri rdoc mysql-server libmysql-ruby ruby1.8-dev irb1.8 libdbd-mysql-perl libdbi-perl libmysql-ruby1.8 libmysqlclient15off libnet-daemon-perl libplrpc-perl libreadline-ruby1.8 libruby1.8 mysql-client-5.0 mysql-common mysql-server-5.0 rdoc1.8 ri1.8 ruby1.8 irb libopenssl-ruby libopenssl-ruby1.8 libterm-readkey-perl psmisc

Gem Installation
Please find latest stable gem version on rubyforge.

wget http://rubyforge.org/frs/download.php/45905/rubygems-1.3.1.tgz
tar xvzf rubygems-1.3.1.tgz
cd rubygems-1.3.1
sudo ruby setup.rb


And last to install rails without documentation

sudo gem install rails --no-rdoc --no-ri

and finally rails server, you can install apache mongrel, nginx + thin, whichever you feel suitable.

for mongrel install

sudu gem install mongrel
Read More…

Fix for ruby 1.8.7 incompatibity

by sandipransing 0 comments
Last week i moved from ruby version 1.8.6 to 1.8.7.
then over a week i found that my 1.2.3 and applications developed in ruby 1.8.6 are not working in ruby 1.8.7.

From lot of search on google, i found that its issue with ruby 1.8.7.

Then, i started searching fix / solution for this incompatibity.
And, Finally i got solution.

We just need to fix file delegate.rb
here is fix

Diff of /branches/ruby_1_8_7/lib/delegate.rb

--- branches/ruby_1_8_7/lib/delegate.rb 2008/05/31 15:17:53 16732
+++ branches/ruby_1_8_7/lib/delegate.rb 2008/06/02 10:52:07 16756
@@ -163,9 +163,9 @@
# Checks for a method provided by this the delegate object by fowarding the

# call through \_\_getobj\_\_.
#
- def respond_to?(m)
+ def respond_to?(m, include_private = false)
return true if super
- return self.__getobj__.respond_to?(m)
+ return self.__getobj__.respond_to?(m, include_private)

end

#
@@ -270,9 +270,9 @@
end
@_dc_obj.__send__(m, *args)
end
- def respond_to?(m) # :nodoc:
+ def respond_to?(m, include_private = false) # :nodoc:
return true if super

- return @_dc_obj.respond_to?(m)
+ return @_dc_obj.respond_to?(m, include_private)
end
def __getobj__ # :nodoc:
@_dc_obj

You have to make necessary changes and you are ready to work with ruby 1.8.7.
need not downgrade ruby version :)

for Hash error

Add following line in config/environment.rb
unless '1.9'.respond_to?(:force_encoding)
String.class_eval do
begin
remove_method :chars
rescue NameError
# OK
end
end
end


Cheers !

Sandip
Read More…

Rails Coding Standards

by sandipransing 1 comments
IN ESSENCE: ALL CODE SHOULD BE READABLE!

# DO NOT OPTIMISE for performance - OPTIMISE FOR CLARITY OF CODE

# STYLE: use 2 spaces for indent (not tabs)

# STYLE: Line up hash arrows for readability

# STYLE: put spaces around => hash arrows

# STYLE: put spaces after ',' in method params - but none between method names and '('

# VIEWS: use HAML for views

# VIEWS: break up the structure with white space to help readability - VERTICALLY TOO!

# VIEWS STYLE: Rely on structure of page, without having to insert messages or new components...

# LOGIC: Rails Models should be as heavy as in logic and controllers should be lightweight as much as .

* Example: Effect to visually highlight then drop out an existing element rather than flash a message

* Example: Highlight newly added row rather than a message about it

# AVOID logic in views - they should be simple

# Views indentation should be well formatted.
not like this

<% for joke in @jokes %>
<div class="joke">
<p>
<%= h(truncate(joke.joketext, 20)) %>
<%= link_to 'Read this joke', {:action => 'show_joke', :id => joke} %>
</p>
<p class="author>
by <%= h(joke.author.full_name) %></p>
</div>
<% end %>


* put html generating logic into helpers

* instead of inline ruby logic, add to models (filtering, checking)

# NEVER use ActiveRecord models in migrations unless you re-define them within the migration

* ...otherwise the migration fails when you later remove/rename the AR class

* BETTER SOLUTION: use bootstrapping until deployed!!!

# AJAX only for sub-components of an object, and avoid over-use




CONTROLLER CODING STANDARDS


1. Before filter should be added at the top of controller.

2. Before filter implementation should be immediate after filter declaration

3. Standard rails actions

4. Own custom actions

5. Inter-related actions should be clubbed together.

6. please, try to use of protected, private methods and they should be declared at the bottom of page in order.

7. Controller Actions should be like -
use 2 spaces for indent (not tabs)

def self.published_jokes
find(:all, :conditions => "published = 1")
end


MODEL CODING STANDARDS


#======= HEADER SECTION=========


# SCHEMA INFORMATION WILL BE HERE
# REQUIRE FILES WILL GO HERE


class Model < ActiveRecord::Base

#======== TOP ===================

# LIBRARY OR INCLUDE METHODS
# MODEL RELATIONSHIPS
# VIRTUAL ATTRIBUTES
# ACTIVE RECORD VALIDATIONS

#======== MIDDLE ===============
# CUSTOM VALIDATIONS
# PUBLIC METHODS

#======== BASE ==================
# PROTECTED METHODS
# PRIVATE METHODS

end

Cheers !!!
Sandip
Read More…

Friday, May 8, 2009

High Performance Rails Hosting

by sandipransing 1 comments
There are lot of rails hosting, like wired tree,...,
i am still in search of cost effective and high performance hosting.

recently i came across with joyent rails hosting, please let me know your opinions..


Scale on Demand

Your rails infrastructure can be dynamically expanded or reduced within minutes.

Support Billions of Hits

The largest ruby on rails application running on Joyent does over 1 Billion page views a month. Joyent's hardware load balancers make this kind of scale possible.
Ruby 1.8.6, Rails 2.1, Mongrel, Nginx

Everything you need to get rolling is pre-installed, including Ruby 1.8.6 and Rails 2.1, Apache, lighttpd, nginx and Mongrel.

Extremely Cost Effective

Static IPs, real storage, 10TB data transfer / bandwidth, and fantastic support all included.
Lightning Fast Speed

We provide direct connections to tier 1 internet back-bones, Force10 switches and f5 BigIP load-balancers.

Trusted by Companies like LinkedIn


Check out their post
Official Ruby on Rails Host

We're the Official Ruby on Rails host. Go check it out at rubyonrails.org. "If you need hosting, Joyent is the official Ruby on Rails host, offering fantastic plans with a knowledgeable staff. Whether you need shared or dedicated hosting, these guys are experts in Ruby on Rails. "
Leverage a Large Community

Over 2,400 companies run Rails applications on Joyent. You gain from our experience hosting them and you can connect directly with them through the Joyent Forums and the Joyent Wiki

Entirely Open Loving Cloud

Joyent offers open protocols, open source solutions. Use any Language, any DB. You can move your application. No vendor lock-in.

please, help me......:(
Read More…

Awesome: Working with the Rails console and all the tricks

by sandipransing 1 comments
Testing your active record methods using script/console

If you are using windows, you start the console by using this command:

ruby script\console
Linux:

./script/console

Just use the following command whenever you make changes to your model objects:

reload!

Instead of accessing your MySQL database with

mysql -u -p

You can instead do

script/dbconsole

and if you database has a password, just do

script/dbconsole -p


% script/dbconsole # connect to development database (or $RAILS_ENV)
% script/dbconsole production # connect to production database


Cheers !

$@ndip
Read More…

using rails acts as taggable on plugin

by sandipransing 1 comments
A tagging plugin for Rails applications that allows for custom tagging along dynamic contexts.

Plugin Installation

script/plugin install git://github.com/mbleigh/acts-as-taggable-on.git

Gem Installation


gem install mbleigh-acts-as-taggable-on --source http://gems.github.com


Auto Install
include following line in environment.rb

config.gem "mbleigh-acts-as-taggable-on", :source => "http://gems.github.com", :lib => "acts-as-taggable-on"


Post Installation (Rails)

1. script/generate acts_as_taggable_on_migration
2. rake db:migrate


Usage
Add following line in your model for which you wanted to be tagged.

acts_as_taggable_on :tags

Example

class Post < ActiveRecord::Base
acts_as_taggable_on :tags
end


In your View for Post




In your controller create action

@post = Post.new (params[:post])
# Or just hardcode to test
@post.tag_list ="awesome, slick, hefty"
@post.save


What are the methods provided ??

@post.tag_list = "awesome, slick, hefty"

Post.tagged_with("awesome", :on => :tags) # => [@post1, @post2]


Post.tag_counts # => [,...]

Named Scope

class Post "created_at DESC"
end


Post.tagged_with("awesome").by_creation

Pagination can be added on list of tags using will_paginate plugin

List Of Tags .paginate(:page => params[:page], :per_page => 20)


@post.find_related_tags # => will give related posts having related tags. [ @post1, @post2, ...]



Tag Owners

class User < ActiveRecord::Base
acts_as_tagger
end



class Post < ActiveRecord::Base
acts_as_taggable_on :tags
end


@some_user.tag(@some_post, :with => "paris, normandy", :on => :tags)
@some_user.owned_taggings
@some_user.owned_tags
@some_post.tags_from(@some_user)



Cheers !
$@ndip
Read More…

About The Author

Sandip is a ruby on rails developer based in pune and also a blogger at funonrails. Opensource contributor and working with Josh software Private Limited. for more info read Follow Sandip on Twitter for updates.

Connect With Me...

Github Projects

Blog Archive

@sandipransing Twitter