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…

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

@sandipransing Twitter