Posts

Showing posts from December, 2011

Basics of Include and Extend in Ruby on Rails

Include is for adding methods to an instance of a class and extend is for adding class methods. Let’s take a look at a small example. module Foo def foo puts 'heyyyyoooo!' end end class Bar include Foo end Bar.new.foo # heyyyyoooo! Bar.foo # NoMethodError: undefined method ‘foo’ for Bar:Class class Baz extend Foo end Baz.foo # heyyyyoooo! Baz.new.foo # NoMethodError: undefined method ‘foo’ for #   As you can see, include makes the foo method available to an instance of a class and extend makes the foo method available to the class itself .

Class and Instance Methods in Ruby

Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is a quick example and then we’ll go into a bit more detail. class Foo def self.bar puts 'class method' end def baz puts 'instance method' end end Foo.bar # => "class method" Foo.baz # => NoMethodError: undefined method ‘baz’ for Foo:Class Foo.new.baz # => instance method Foo.new.bar # => NoMethodError: undefined method ‘bar’ for #   Class Methods Ruby is very flexible and as such it allows several ways to define a class method. The following is a sample of the most commonly used ways. # Way 1 class Foo def self.bar puts 'class method' end end Foo.bar # "class method" # Way 2 class Foo class << self def bar puts 'class method' end end end Foo.bar # "class method" # Way 3 class Foo; end def Foo.bar puts 'clas

Play with Rails Console

app is another local variable which is avaliable to you,  It’s a local variable you get for free in script/console . An instance of ActionController::Integration::Session $ ruby script / console Loading development environment .   >> app . url_for ( :controller => ' stories ', :action => ' show ', :id => ' 10002 ') => " http://www.example.com/stories/10002 "   >> app . get ' /stories/10002 ' => 200   >> app . assigns ( :story ) => #<Story:0x24aad0c ... >   >> app . path   => " /stories/10002 "   >> app . reset!   => nil   >> app . get ' /yeah/right/dude ' => 404   >> app . post ' /account/login ', { :username => 'username ', :password => 'password ' } => 200   >> app . cookies => {" _session_id "=>" 9d1c014f42881524ff6cb81fb5b594

Helpers in Rails Console

Rails gives you a helper local variable to play with. $ ruby script / console Loading development environment .   >> helper . pluralize 2 , " story " => " 2 stories "   >> helper . submit_tag => " <input name= \" commit \" type= \" submit \" value= \" Save changes \" /> "   >> helper . visual_effect :blindUp , ' post ' => " new Effect.BlindUp( \" post \" ,{}); "

Rails Array Methods

to_sentence (Array) >> %w[Chris Mark Steven].to_sentence => "Chris, Mark, and Steven"    You can pass it two options: :connector and skip_last_comma. They work like a’this: >> %w[Soap Mocha Chocolate].to_sentence(:connector => '&') => "Soap, Mocha, & Chocolate"  >> %w[Ratatat Interpol Beirut].to_sentence(:skip_last_comma => true) => "Ratatat, Interpol and Beirut"    to_param (Array) >> helper.url_for :controller => 'users', :action => 'show', :id => %w[one two three] => "/users/one%2Ftwo%2Fthree" in_groups_of (Array) >> %w[1 2 3 4 5 6 7].in_groups_of(3) { |g| p g } ["1", "2", "3"] ["4", "5", "6"] ["7", nil, nil] >> %w[1 2 3].in_groups_of(2, ' ') { |g| p g } ["1", "2"] ["3", " "] >> %w[1 2 3].in_groups_of(2

Rails String Shortcuts and Methods

at (String) >> "Finally, something useful!".at(6) => "y" from and to (String) >> " Chris the Person ". from ( 6 ) => " the Person " >> " Chris the Person ". to ( 4 ) => " Chris "   first and last (String) >> " Christmas Time ". first => " C " >> " Christmas Time ". first ( 5 ) => " Chris " >> " Christmas Time ". last => " e " >> " Christmas Time ". last ( 4 ) => " Time "       each_char (String) >> " Snow ". each_char { | i | print i . upcase } SNOW starts_with? and ends_with? (String) >> " Peanut Butter ". starts_with? ' Peanut ' => true >> " Peanut Butter ". ends_with? ' Nutter ' => false to_time and to_date (String)   >> " 1985

A Complete Rails Cheat Sheet in your Console

A Complete Rails Cheat Sheet in your Console A Complete help no need to search any where else just few steps First you need to install cheat gem sudo gem install cheat Then try using cheat commands like cheat svn and this will show, you can try git, strftime and my favorite  migrations !! enjoy !! nishant@ubuntu:~/home/Application$ cheat svn svn: Creating a new repository: mkdir /path/to/new/dir svnadmin create /path/to/new/dir Starting svnserve: svnserve --daemon --root /path/to/new/repository Importing project into svn repo: $ svn import -m "Wibble initial import" svn://olio/wibble/trunk Creating directory in svn repo: $ svn mkdir -m "Create tags directory" svn://olio/wibble/tags Branching: $ svn copy http://svn.example.com/repos/calc/trunk \ http://svn.example.com/repos/calc/branches/my-calc-branch \ -m "Creating a private branch of /calc/trunk." Committed revision 341.

Secrets of Rails Console and Tricks

Reloading the console When you make some changes your models and need to see those changes reflected in your Rails application in a web browser you just hit Reload Or refresh the whole page. In development  mode, the Rails application loads all the files anew every single time a page is requested. The same is true for the console—but it loads the files anew every time you start the console, instead of per page request. To avoid having to quit and reopen the console every time you change your application’s code, simply type the follow command: >> Dispatcher.reset_application!   Or, better yet: >> reload!   This is what you’ll see: >> reload! Reloading...   Rollback all database changes on exit How to run the console in a sandbox—meaning that all your database changes are completely reverted when you exit the console. Basically, it looks like this: $ script/console --sandbox Loading development environment in sandbox. Any modi

Apache Solr Installation on linux : Complete Setup

Installing Tomcat 6 in Ubuntu 10.04 and Libmysql-java: $ sudo apt-get update && apt-get upgrade $ sudo apt-get install tomcat6 tomcat6-admin tomcat6-common tomcat6-user tomcat6-docs tomcat6-examples $ sudo apt-get install libmysql-java Download apache-solr-1.4.1.tgz from http://lucene.apache.org/solr/ and extract it: $ cd $ sudo cp apache-solr-1.4.1/dist/apache-solr-1.4.1.war /usr/share/tomcat6/webapps/solr.war $ sudo cp -R apache-solr-1.4.1/example/solr/ /usr/share/tomcat6/solr/ note : we copy solr folder into /usr/share/tomcat6 and it will pointed as solr home in next step. Create new Solr configuration in Tomcat6: $ sudo vim /etc/tomcat6/Catalina/localhost/solr.xml Paste this into file : Enable MultipleCore in Solr 1.4.1: $ sudo cp apache-solr-1.4.1/example/multicore/solr.xml /usr/share/tomcat6/solr/solr.xml $ sudo cp -R apache-solr-1.4.1/example/multicore/core0 /usr/share/tomcat6/solr/ $ sudo cp -R apache-solr-1.4.1/example/multicore/core1 /usr/s

Apache Solr Installation : Steps

sudo apt-get update && apt-get upgrade sudo apt-get install tomcat6 tomcat6-admin tomcat6-common tomcat6-user tomcat6-docs tomcat6-examples sudo apt-get install libmysql-java wget http://lucene.apache.org/solr/ sudo tar -zxvf apache-solr-1.4.1.tgz sudo cp apache-solr-1.4.1/dist/apache-solr-1.4.1.war /usr/share/tomcat6/webapps/solr.war sudo cp -R apache-solr-1.4.1/example/solr/ / usr/share/tomcat6/solr / sudo nano /etc/tomcat6/Catalina/localhost/solr.xml (and paste the code :- <Context docBase="/usr/share/tomcat6/webapps/solr.war" debug="0" privileged="true" allowLinking="true" crossContext="true"> <Environment name="solr/home" type="java.lang.String" value="/usr/share/tomcat6/solr" override="true" /> </Context>) sudo cp apache-solr-1.4.1/example/multicore/solr.xml /usr/share/tomcat6/solr/solr.xml sudo cp -R apache-solr-1.4.1/example/multicore/co

Make Dynamic Paths for Paperclip in Ruby on Rails application

For creating Dynamic paths , we need to overwrite the Paperclip::Interpolations module of paperclip and we will add a new method like user_id etc and this will return that dynamic value which will be used to create a dynamic path. config/initializers module Paperclip module Interpolations def user_id attachment, style_name attachment.instance.user_id end end end    And now we can use :user_id in our path    has_attached_file :user_image :url => "../assets/users/:user_id/#{self.name}_:basename_:id" + ".:extension", :path => ":rails_root/public/assets/users/:user_id/#{self.name}_:basename_:id" + ".:extension"  

ImageMagick Installation with PNGlib and JPEGlib

Unpack the distribution with this command: tar xvfz ImageMagick.tar.gz Next configure and compile ImageMagick: cd ImageMagick-6.7.4 With every installtion there is a read me file like install-unix.txt , from there you will find the options to add additional libraries like png and jpeg , so you need to make change in configure command with those options. ./configure --with-jpeg=yes --with-png=yes --with-tiff=yes --with-freetype=yes  --with-fontconfig=yes --with-modules=yes --enable-shared=yes make If ImageMagick configured and compiled without complaint, you are ready to install it on your system. Administrator privileges are required to install. To install, type sudo make install You may need to configure the dynamic linker run-time bindings: sudo ldconfig /usr/local/lib Finally, verify the ImageMagick install worked properly, type /usr/local/bin/convert logo: logo.gif          

Renaming Application on Heroku along with Url

First you need to login to Heroku from command line using this command $ heroku login    Please follow this link Heroku : Complete Setup Then, You can rename an app at any time with the heroku rename command. For example, to rename an app named “oldname” to “newname”, change into the app’s git checkout and run: $ heroku rename newname http://newname.heroku.com/ | git@heroku.com:newname.git Git remote heroku updated   Renaming an app will cause it to immediately become available at the new subdomain ( newname.heroku.com ) and unavailable at the old name ( oldname.heroku.com ). This may not matter if you’re using a custom domain name, but be aware that any external links will need to be updated.

Heroku Application with Custom name and Url

If you would like to create a New Application with your own name for free on Heroku Please follow this link Heroku : Complete Setup If you wanted to create a new application with your custom name , First you need to login to Heroku from command line using this command $ heroku login After that you need to enter your credentials email address and password. Once you logged in you need to run this command $ heroku create myapp Created http://myapp.heroku.com/ | git@heroku.com:myapp.git Git remote heroku added   Using this command you can create a new application with custom name and url Creating an App Without a Name The app name argument (“myapp”) is optional. If no app name is specified, a random name will be generated. $ heroku create Created http://mystic-wind-83.heroku.com/ | git@heroku.com:mystic-wind-83.git

Interview Question on Ruby on Rails

1 .  Why Ruby on Rails? Ans: There are lot of advantages of using ruby on rails DRY Principal Convention over Configuration Gems and Plugins Scaffolding Pure OOP Concept Rest Support Rack support Action Mailer Rpc support Rexml Support 2. Explain about the programming language ruby? Ruby is the brain child of a Japanese programmer Matz. He created Ruby. It is a cross platform object oriented language. It helps you in knowing what your code does in your application. With legacy code it gives you the power of administration and organization tasks. Being open source, it did go into great lengths of development. 3. Explain about ruby names? Classes, variables, methods, constants and modules can be referred by ruby names. When you want to distinguish between various names you can specify that by the first character of the name. Some of the names are used as reserve words which should not be used for any other purpose. A name can be lowercase letter, upper case lette