Ruby Cheat-Sheet

Hi Folks,

In this new tutorial, I am going to show you what most of developers/programmers already know, but not able to keep track of such things. I call it as ‘Ruby cheat-sheet‘, you can call it by the name you like.

This will also help those people who have just started learning ‘Ruby’.

IMPORTANT NOTE:

  • I will keep on updating this article frequently.
  • Also need your valuable response, if you feel there is a better/easy concept available.
  • If I am not sure of something or don’t know the concept, I am going to highlight that with ‘Red‘ color. Later, you can put your opinion in the comment section and I will update that with your name.
  1. Symbols (e.b :name, :age etc.) as just a convenient way of referencing a name.
  2. You don’t need to per-declare a symbol.
  3. A ‘Class‘ is a combination of state (for example, the name of the animal) and method that use that state (perhaps the method how animal eats).
  4. The standard ruby constructor is ‘new‘.
  5. Every object in Ruby has a unique ‘Object identifier‘ (called as Object ID).
  6. Class have instance methods. These instance methods have access to the object’s instance variables.
  7. Methods are defined with the keyword ‘def‘ followed by method name.
  8. The most common way to create String objects in Ruby is ‘string literals‘. (E.g. “I am a string”, ‘I am another string’)
  9. The logical difference between ‘Single quotes‘ and “Double quotes” in Ruby is the amount of processing Ruby does. In double quote case, Ruby first looks for substitution and replaces them with some binary value. (E.g. puts “Good Night, \nAuthor”)
  10. Global variables: starts with ($) sign: E.g. $name
  11. Instance variable: starts with (@) sign: E.g. @name
  12. Class variables: starts with (@@) sign: E.g. @@name
  13. Class name, module name and Constants: Starts with the uppercase letter: E.g class MyClass, module Login
  14. Array stores collection of object with a key to access them.
  15. An array can have objects of different types.
  16. Hash contains key, value pair.
  17. Ruby treats ‘nil’ as false in conditions.
  18. A regular expression is a way of specifying a pattern of characters to be matched in a string.
  19. The match operator (=~) can be used to match a regular expression against a string.
  20. Yield (yield) is a Ruby method
  21. In Ruby, nil is also an Object
  22. When you run Ruby programs you can actually pass arguments. This concept is called command-line-arguments. For e.g. ruby my_example.rb firstname lastname city.
  23. The initialize method in Ruby lets us set the state of each object. When we call ClassName.new to create a new object, Ruby allocates some memory to hold an UN-initialized object.
  24. When we pass an object to puts based on the class, it writes the name of the object’s class, followed by a colon and a unique identifier.
  25. Ruby gives flexibility to its programmers. You can over-write the default methods. (E.g. def to_s)
  26. attr_reader is the modified way of accessor methods.
  27. attr_accessor provides you to read and write methods. (E.g. attr_accessor :age)
  28. Virtual attributes**
  29. require‘, ‘require_relative‘ & ‘load
  30. Access Controls – ‘Public‘, ‘Private‘ & Protected
  31. In ‘Ruby’ a variable is not an Object. It is simply reference to an Object.
  32. initialize‘ is a private method in Ruby.
  33. Block, Procs and Lambda are ways of grouping code we want to run. These are examples of closure in Ruby.
  34. Both Proc and Lambda are Proc Objects.
  35. Lambda check the number of arguments and throws argument error, whereas Proc does not.
  36. In “Inheritance“, if class B inherits the property of class A, then all the methods of class A becomes the member of class B.
    • Assuming child = Child.new; then child.superclass => Parent
    • parent.superclass => Object
    • Object.superclass => BasicObject
    • BasicObject.superclass => nil
  37. Modules: is a way of grouping together Methods, Classes and Constants.
    • Provide namespaces and prevent name clashes.
    • Supports the mix-in functionality.
    • A Module is not a class.
    • A Module cannot have instances.
    • We can always include a module in a class definition – After doing that all module instance methods are suddenly becomes available as methods in the class. They get mix-in.
    • mix-in modules don’t use instance variable directly. They use accessors to retrieve data.
  38. self.method_name: Gives you access to the current object.
  39. begin-rescue blockUse for exception handling.
  40. begin
    # Code to be executed here
    # This part will be 'protected'
    raise # Use this to raise any message
    rescue
    # Exception Handling, like argument error, 404
    retry # use this if you want the begin block to be executed again, if execption occurs.
    ensure
    # This part will always get executed.
    end

    view raw
    block.rb
    hosted with ❤ by GitHub

Rails 3: Polymorphic Associations in Action

Hi Folks,

In this short article, I would like to brief about “Rails polymorphic associations“. Below are the high-level pointers.

  • What is Polymorphic Association
  • How Rails handles it
  • Example explained
  • Demo

So, Let’s start:

  • What is Polymorphic Association: In OOP, Polymorphic means “of-many“.

There is a well documented and well explained Railscasts for this. Refer to this link for more information: http://railscasts.com/episodes/154-polymorphic-association

  • Example Explained:
class User < ActiveRecord::Base
attr_accessible :email, :name
has_many :comments, :as => :commendable
end
class Event < ActiveRecord::Base
attr_accessible :name, :organizer, :place
has_many :comments, :as => :commendable
end
class Comment < ActiveRecord::Base
attr_accessible :comment
belongs_to :commendable, :polymorphic => true
end
# Migration: create_comments.rb
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.text :comment
t.references :commendable, :polymorphic => true
t.timestamps
end
end
end

view raw
gistfile1.rb
hosted with ❤ by GitHub

Code snippet can be downloaded from Github. The path for the same is: git@github.com:puneetpandey/rails3_singleTableInheritance.git

Once set-up. Type the URL’s below:

  1. http://localhost:3000/events
  2. http://localhost:3000/users

Rails 3: Single Table Inheritance

Hi Folks/Fellow Developers,

As I’ve seen lot many examples, articles over Single Table Inheritance, I decided to write my own. Thanks to the open source contributors. Their Articles/Examples helped me a lot writing this post.

As you might know about single table inheritance, let me quickly set the definition for it. Single-Table-Inheritance (STI) allows you to write/create sub-classes of a specific model. You can use a single table, add specific objects and extend the functionality/behavior of base model.

Current example explained:

My Current example is based on Mobile system. We have a single model called ‘Mobile’ and other models such as ‘Samsung’, ‘Apple’, ‘Nokia’ etc., that inherits the property of Mobile model. (Refer to the image for more help)

Single Table Inheritance
Single Table Inheritance

Development Platform used:

Ruby - 1.9.3
Rails - 3.2.13
Bundler- 1.3.5
DB - MySQL
IDE - Netbeans 6.9.1

The application is currently hosted on GitHub and can be cloned using the below command:
git clone git@github.com:puneetpandey/rails3_singleTableInheritance.git

Let me know your feedback about this application.

Happy Coding!
Puneet

How to index multiple documents with Solr

Hi Folks,

Hope you all are fine and doing good. Few weeks back, I was looking into solr to see if it index multiple attachments! The requirement was very simple: A user will upload multiple files and solr will index those. I tried finding the solutions on the internet but found very basic ones.

Now, I am sharing my experience with you all with some code snippet, which will tell how to index multiple documents/attachments with Solr.

Model: job.rb

has_many :job_attachments
accepts_nested_attributes_for :job_attachments, :allow_destroy => true

Model: job_attachment.rb

belongs_to :job
has_attached_file :attachment

searchable :auto_index => false do
attachment :document_attachment
end

private
def document_attachment
"#{Rails.root}/public/#{self.attachment.url}"
end

So what this code snippet does? Whenever you run rake sunspot:reindex, it will index multiple files uploaded by a user.

Handling at controller side:

sunspot_str = params[:search]
search = Sunspot.search [Job, JobAttachment] do
fulltext sunspot_str, :minimum_match => 1
end
puts search_result = search.results

Hope this will help someone! Happy coding

FREEZE GEMS IN RAILS 3 APPLICATION

I have seen lots of forum, where developers keep on asking: “How would I freeze the gems to my Rails-3 application?”

Take this URL for example: http://bit.ly/gFzN6Z

One developer says that: localize your gems by running this command: bundle install –vendor/gems

Others refuses to go with this way. Here’s why?

  • We are moving away from the concepts of bundler
  • This will install the gem dependencies as well in your vendor/gems directory, which we don’t need at all. We need only those gems which are specific to our application.
  • You don’t need to unpack the gems and check them in to your app, because it doesn’t matter: you’re guaranteeing the same versions are being called regardless of where they are installed, which will likely vary from machine to machine anyways (.bundle/ should not be checked in to the repo) – so why stick another 60-80 MB of files into your repo that you won’t ever be changing or using?

So, there is no way you can localize your gems in a Rails-3 application. There are other ways you can perform in order to better use of bundler gem.

  • Use specific versions in your Gemfile and run bundle install –deployment on each target system where you need the exact gem versions.
  • While defining a new gem in Gemfile, assign a path to it. For example:
    gem 'paperclip', '2.3.15', :path => './vendor/gems/paperclip-2.3.15'
    Bundler will assume that it has to get the gem from vendor/gems folder. Once you’re done. run bundle install

CUSTOM VALIDATION IN PAPERCLIP

In this short tutorial, I will explain you how you can add custom validation messages on the Attachment if you’re using Paperclip plugin or gem.

Way 1. This will work if you’re running your rails application on Windows Machine.
Solution: a) install mimetype-fu plugin.
b) Once installed, open Model, where paperclip settings has been defined. In my case, its User Model. Open it and add:

has_attached_file :avatar
validate :prohibited_ext
protected
def prohibited_ext
errors.add(:avatar, “Format #{File.mime_type?(avatar.path)} is invalid!”) unless File.mime_type?(avatar.path) == “application/exe”
end

UPGRADE RAILS PERFORMANCE

In this article, we will try to Enhance our rails application performance.

To know, how is your rails application is performing on different environments, you must need some plugin or gem. There are many gems/plugins already available which you can use and analyze the performance.

First of all, I would like to list down those, which I will cover in my next tutorials.

Once you configure anyone of those, you’ll come to know how is your rails application is performing. I personally advise to use New Relic or Rack-Bug.

There are several ways, where you can upgrade you rails application performance. Let’s see what are those and how they work…

  • Enable Caching
  • Load Less SQL Queries
  • Avoid using before_filter for loading heavy data

JOINS IN SQL

Sometimes, its very hard to keep Joins concept in mind.. Being a beginner, experienced SQL programmer, you should know the concept of JOINS.

In this article, I will show you the difference between:
1. JOINS and INCLUDE
2. How to you use JOINS in rails
3. JOINS over INCLUDE
4. JOINS and INCLUDE in RAILS-3

Let’s cover them in detail:
What is Join ?
The SQL JOIN clause is used whenever we have to select data from 2 or more tables.

To be able to use SQL JOIN clause to extract data from 2 (or more) tables, we need a relationship between certain columns in these tables.

Joins Type
1. OUTER JOIN
1.a. LEFT OUTER JOIN
1.b. RIGHT OUTER JOIN
2. Inner Join

Let’s take an example here:

<images comes here />

The INNER JOIN will select all rows from both tables as long as there is a match between the columns we are matching on. In case we have a customer in the Customers table, which still hasn’t made any orders (there are no entries for this customer in the Sales table), this customer will not be listed in the result of our SQL query above.

The second type of SQL JOIN is called SQL OUTER JOIN and it has 2 sub-types called LEFT OUTER JOIN and RIGHT OUTER JOIN.

The LEFT OUTER JOIN or simply LEFT JOIN (you can omit the OUTER keyword in most databases), selects all the rows from the first table listed after the FROM clause, no matter if they have matches in the second table.

So, far you must be cleared with what JOIN does!! Now, we will see what JOINS and INCLUDE gives us….

Consider these two statements:

User.find(:first, :include => :user_profiles)
User.find(:first, :joins => :albums)

<I am going to update this post soon.>

SEND TWEETS FROM RAILS APPLICATION

So, we’re continuing from here: https://puneetitengineer.wordpress.com/2009/08/12/send-tweets-fr…ls-application/

So far we’ve covered the basics of it, now its time to create some controllers…. Open your command/terminal and fire this command:

ruby script/generate controller twitt

Once you’re done, open this file and write the below code inside it:

class TwittController < ApplicationController

gem(‘twitter4r’, ‘>=0.2.0′)
require ‘twitter’
require ‘twitter_search’
require ‘rubygems’
before_filter :authorize, :except => [:login, :authenticate, :save_users, :twitter_cred]

def login
@user = User.new
end

def authenticate

@user = User.new(params[:user])
client = Twitter::Client.new
if client.authenticate?(@user.username, @user.password)
@username = User.save_users(params[:user])
session[:user_id] = @user.id
session[:username] = @user.username
session[:password] = @user.password
redirect_to :action =>’post_status’
else
render :action =>’login’
end

end

end

Now, open /app/views/twitt/login.html.erb and paste below lines:

<% form_for :user, :url => { :action => :authenticate } do |form| %>

<%= label :user, :username, “UserName:” %>
<%= form.text_field :username, :size => 30 %>

<%= label :user, :password, “Password:” %>
<%= form.password_field :password, :size => 30 %>

<%= submit_tag “login” , :class => “submit” %>
<% end %>

INTEGRATE ORACLE WITH RUBY

Since most of the rails application is now using various databases, this article will show you how you can useORACLE database with rails.

For that, we need Oracle XE

I will update this post as soon as I can…. Apologize for the dealy. However, you can mail me any of your query if you are stuck in configuring Oracle with Rails.