Hello Everyone,

We all know basic concepts of Ruby, like classes, objects, methods etc. etc and we integrate this with the concept of rails beautifully.

In short I can say we all are very good at Ruby on Rails, and rails specially, but when it comes to Ruby, we are not that much confident tough.

In this Post of mine, we will cover all the important concepts of Ruby, some pure ruby code, and how we can apply this with Rails.

So let’s start learning the Core Ruby Concepts.

  • In RoR programming, most of the times we need to identify the type of string. We don’t know if the incoming string is a “Integer”, “Float”, “String”. To check that:
    y = Incoming String
    y.is_a?(Integer) => returns true or false
    y.is_a?(String) => returns the same
    y.is_a?(Fixnum) => -----#-------
    y.is_a?(Float) => -----#-------

    • We can also ask the variable exactly what class of variable it is using the class method:
      y = "Incoming String"
      y.class => returns String
      y = 10.25
      y.class => returns Float
      y = 10 => returns Fixnum
    • Sometimes we need to change the incoming string to say Integer (Note: It is for sure that in RoR application, when browser sends any parameter to any controller’s method, it will be string only), Float for further operations. To do that:
      x = "10.25"
      y = x.to_f
      p y.class => returns Float
      z = y.to_i
      p z.class => returns Fixnum
  • Variable type: Ruby has four types of variables:
    • Local variable [a-z] or _
    • Global Variable $
    • Instance variable @
    • Class variable @@

    To identify the type of variable, do:
    a = 10
    p defined?(a) => "local-variable"
    $b = "Puneet"
    p defined?($b) => "global-variable"

  • Metaprogramming: Metaprogramming is a technique in which code writes other code. The prefix Meta refers to Abstraction.
    • At a high level, metaprogramming is useful in working towards DRY principle (Don’t Repeat Yourself).
    • Metaprogramming is primarily about simplicity. One of the easiest ways to get a feel for metaprogramming is to look for repeated code and factor it out. Redundant code can be factored into functions; redundant functions or patterns can often be factored out through the use of metaprogramming.

Hello Everyone,

Today, where lots of people are shifting from older versions of ruby to the newer and stable one i.e 1.9.2 and rails 3. I am also shifting to this, and would like to share my thoughts and opinions about upgrading, its advantages, hurdles and future concerns.

To try this.. I am using both Linux (Ubuntu) and Windows (windows 7).
Let’s cover each topic in detail

  • Setting up Ruby-1.9.2
  • What’s new in Ruby-1.9.2
  • Few of the working ruby code
  • Setting up Rails-3 with Ruby-1.9.2
  • Setting up Passenger or Apache with Rails-3
  • A sample application in Ruby-1.9.2 and in Rails-3, featuring:
      Authentication
      Image Upload
      Pagination
      Facebook Integration
      Twitter Integration
      Google Earth integration
      Post with Title and tags

I may cover this using different articles.

Meanwhile, there is an Rails-3 Application created by me, which is currently on Github. I would request, if someone is interested to see the changes Rails-3 has introduced, please download the application and run it on your local. Here is the path for it: https://github.com/puneetpandey/file_upload

Prerequisites:
1. Ruby 1.8.7 or higher
2. Rails-3
3. Mysql Database

Hello Everyone,

In this article we will cover how to run your rails-2+/3 application on Heroku.

Requirements:
1. Heroku Account (http://heroku.com/)
2, Github Account (http://github.com/)
3. Heroku Gem (gem install heroku)
4. msysgit
5. Latest version of Git

Steps:
Step 1: Download msysgit and run it. Once the installation is finished. Create your SSH Public key (if it has not created before.)
Steps on creating SSH keys can be found here:
Step 2: Once you’re done with SSH keys, Login into your Github Account and go to Account Settings -> SSH Public Keys. Copy your id_rsa.pub key and paste it there.
Step 3: Install latest version of Git, and make sure you have “checked“- access GIT via Command Line.
Step 4: Install heroku gem
Step 5.a: If you’re committing your application for the first time in GIT, do these steps:
5.a.1 git init
5.a.2 git add
5.a.3 git commit -m “my new app”
5.a.4 heroku create
5.a.5 git push heroku master

During these steps, heroku will ask for your credentials. Give your username and password when asked. Once you’re done with all these steps, you can check “My Apps” under your Heroku Account. There you’ll find a link to access your application.

For all, who have started learning RoR and for those who are into this, here are some of the facts and conventions that you can follow, to make your Ruby code more shorter and easy to understand.

Let’s look at it how:

1. This is how a beginner writes:
if params[:email]
@email_add = params[:email]
else
@email_add = “Some Default Address”
end

You should write in 1 line, let’s see how:
@email_add = params[:email] ? params[:email] : “Some Default Address”

2. How to Improve the performance of any method inside your controller, if it is taking much time rather than the expecting.

Consider a scenario where we have one method, like:
def index
@users = User.find(:all)
@members = Member.find(:all)
@last_year_users = User.find(:all, :conditions => ["Some condition"])
end

Now here suppose these queries returns data in a heavy size, definitely it will gonna take time to load, so how we will improve the performance in this case?

3 How to update ruby 1.8.6 to 1.8.7 or 1.9?
This makes me frustrated most of the times. I am having Ruby 1.8.6 as a stable version on my system. Now I want to update it to 1.8.7 so that I can sense Rails 3.0 and its features, but most of the sites and blogs are giving instructions to install it as a fresh copy and most of the sites are giving information that 1.8.7 is not compatible with rails 2.1 or higher.

So If someone knows how to upgrade, so that It won’t affect my existing apps running on 1.8.6 and it will install both copies of Ruby like rails does, please do post it here. I’ll be very thankful

4. Using polymorphic and as associations with models
Now, for most of the programmers, consider a scenario where multiple models has 1 to N relationship with one model. To make it more easier lets take 1 example.

Consider the following diagram:

Where models like School, College, Event and Semester are having multiple relationship with a single model i.e Student. Do you think, our student model will have foreign keys like school_id, college_id, event_id and semester_id? Will it be a good idea to have multiple foreign keys into one table?
No it doesn’t make any sense. So whenever you have a scenario like this, you have to follow polymorphic and as associations. How? Let’s see:
In Your models i.e school.rb, college.rb, semester.rb and event.rb, define something like this:

class School < ActiveRecord::Base
has_many :sc_students, :class_name => “Student”, :as => :rollable, :dependent => :destroy
end

class College < ActiveRecord::Base
has_many :col_students, :class_name => “Student”, :as => :rollable, :dependent => :destroy
end

class Semester < ActiveRecord::Base
has_many :sem_students, :class_name => “Student”, :as => :rollable, :dependent => :destroy
end

class Event < ActiveRecord::Base
has_many :ev_students, :class_name => “Student”, :as => :rollable, :dependent => :destroy
end

class Student < ActiveRecord::Base
belongs_to :rollable, :polymorphic => true
end

So, what is the advantage here to use as association and polymorphic is, you don’t need to create school_id, college_id, semester_id and event_id columns in the students table. So when you create migration, you’ll have to create two columns i.e.

t.integer :rollable_id
t.string :rollable_type

So for example colleges the entry will have rollable_id as specific college id and rollable_type as “College”. How simple and short implementation, isn’t it?

Well, this must be common to all, as all of us has implemented this kind of feature somewhere in our projects.. But I found it challenging couple of times to implement this.. so I thought to share this small piece of code with you. Hope it helps someone..

Requirement: In this small project we are going to store multiple arrays into the database as each array will create a new row.

Let’s see how it works..

Here is my view(in your case it could be any)

<select name=”contacts_id[]” id=”contacts_id”>
<% current_user.contacts.all.each do |contact| %>
<%= contact.name %>
<% end %>
<%= channel.name %>

Now in this case we have two arrays one is for contact_id and another one is for channel_id, Let’s see how we will store those values into the table:

def create
@contacts_channels = []
params[:contact_id].each_with_index do |contact, i|
@contacts_channels[i] = ContactChannel.new
@contacts_channels[i].contact_id = contact_id
@contacts_channels[i].channel_id = params[:channel_id][i]
@contacts_channels[i].save
end
end

So what happens here? suppose you have an array of contact_id like this:
contact_id = [4,5,6]
and array of channel_id like this:
channel_id = [10, 11, 12]

So with the above script your values should go into the table like this
contact_id channel_id
4 10
5 11
6 12

What makes me puzzled here is, in case of relationship here like
Contact has_many :channels
how will this exact scenario works?

Please let me know your feedbacks, suggestions and queries. Your comment means lot to me.

Programmers who work mostly on windows have seen this kind of errors many times.. as a windows programmer I have been through many sites and collect d relevant data, now I am showing it to you..

The errors which might come to you something like this:
no such file to load mysql
rake aborted: no such file to load mysql
The bundled mysql.rb driver has been removed from Rails 2.2. Please install the mysql gem and try again: gem install mysql
Could not find RubyGem rake-compiler (~> 0.5)

To solve such problems follow these steps:
Step 1. Update rubygems to the latest version(like I upgraded it to 1.3.5).
Step 2: install rake-compiler(by gem install rake-compiler).
Step 3: if already installed hoe gem update it(gem update hoe) or install a fresh one.
Step 4: Download libMySQL.dll from here and copy it into C:/ruby/bin or wherever your ruby is installed, but make sure it should be in bin directory.
Step 5: Stop the mysql service, from Control Panel -> Administrative tools -> services -> mysql, and then restart it.

That’s it. You are done, after all these steps you can try
rake db:migrate
Suppose if that doesn’t work then after 4th step, stop the mysql service and restart your system.

I welcome all of you to post your comments, feedbacks, queries

Cheers!!
Puneet Pandey

Hey all,

I hope this article will help you if you want to send tweets from your rails application. I have used couple of gems and plugins for that, will describe you those in this tutorial.

AIM: We have a rails application which will allow twitter user to log-in. Once the user logged-in he/she can send tweets from your rails application.

DEPENDENCIES: 1. geokit-rails [Plugin]
2. ym4r-gm [Plugin]
3. twitter4r [Gem]
4. twitter-search [Gem]
5. twitter-console [Gem]
6. google-geocode [Gem] [Optional]

INSTALLATION:
1. Install twitter4r (gem install twitter4r[for windows user], sudo gem install twitter4r[for linux users])
2. Install twitter-search (sudo gem install dancroak-twitter-search -s http://gems.github.com)
3. Install twitter-console *for linux users only
[Follow this: http://www.fsckin.com/2008/03/31/twitter-clients-for-linux/]
[and this: http://blog.guillermoamaral.com/2007/03/18/twitter-console-update/]
4. Install google-geocode (sudo gem install google-geocode)
5. Install goekit-rails
5.1 ruby script/plugin install git://github.com/andre/geokit-rails.git
5.2 Add this line to your environment.rb: config.gem “geokit”
5.3 Tell Rails to install the gem: rake gems:install
(for more details visit this link: http://github.com/andre/geokit-rails/tree/master)
6. Install ym4r_gm (ruby script/plugin install svn://rubyforge.org/var/svn/ym4r/Plugins/GM/trunk/ym4r_gm)
[if you get trouble in installation follow this: http://ym4r.rubyforge.org/]

So we have a base setup for our rails application. Now lets have some code.
First of all lets create few models as well as migrations tables:
1. ruby script/generate model Keyword
2. ruby script/generate model Location
3. ruby script/generate model Post
4. ruby script/generate model User
5. ruby script/generate model Techtwit
6. ruby script/generate migration sessions

After creating all the above steps lets create some columns for our tables:
1. for keywords: timestamps
2. for locations: address:text, timestamps
3. for posts: message: text, timestamps
4. for users: username:string, password:string
5. for techtwits: twitter_id:string, timestamps
6. for sessions: session_id:string, data:text, timestamps
6.1 add_index :sessions, :session_id
6.2 add_index :sessions, :updated_at

Follow this Tutorial to finish-off this application.

Does it looks odd?? You have so many websites which allows you to minimise your url like tinyurl, bit.ly etc etc list is endless, but what if you get some API of those to work with so you can minimise the url with your rails application or as a stand-alone ruby program??

Bit.ly comes with that. It provides ruby programmers an interface by which they can minimise the url. Wondering How? see it in action..

I am creating a simple ruby program here, if you want you can use it in your application…

All you need is json and open-uri to finish it off.

require ‘open-uri’
require ‘json’

code=’https://www.google.com/accounts/ServiceLogin?service=mail&passive=true&rm=false&continue=http%3A%2F%2Fmail.google.com%2Fmail%2F%3Fui%3Dhtml%26zy%3Dl&bsv=zpwhtygjntrz&scc=1&ltmpl=default&ltmplcache=2&hl=en’
user=’YOUR USERNAME’
apikey=’YOUR API KEY’
version=’2.0.1′
url = “http://api.bit.ly/shorten?version=#{version}&longUrl=#{code}&login=#{user}&apiKey=#{apikey}”
buffer = open(url, “UserAgent” => “Ruby-ExpandLink”).read
result = JSON.parse(buffer)
shorturl = result['results']['shortUrl']

That is it. Run this program in console/command prompt, where ever you want to see the output.

Post your queries, suggestions
Puneet

Hi guys,

Its been a long time since I posted any article. This time I come up with Interesting Tutorial which is Bulk Upload. Normally in most of the sites we have seen that there is a file upload field where we can upload a zip file and it will extract automatically.

Now the Point is How it can be done is Ruby on Rails? The answer is very simple, all we need are two gems + few lines of code. Wondering How?? See this in action…

Install two gems first:

for Linux Users:

1. sudo gem install rubyzip

2. sudo gem install fastercsv

for windows users: remove sudo and install above gems.

now open up your rhtml page and write down the following code:

<% form_for :file_upload,:url => {:controller=>'bulkupload',:action=>'upload_file'}, :html => { :multipart => true, :target => "frame", :id => "file_upload" } do |f| %>
<input type="file" name="file_upload_product[file_name]"/>
<input type="submit" value="Upload"/>
<%end%>

Now Open up your bulkupload controller and create method upload_file in that

require 'faster_csv'
require 'fileutils'
class BulkuploadProductController < ApplicationController
  def bulk_upload
    begin
     @file=FileUpload.new
     @file.file_name=params[:file_upload_product]['file_name']
     if @file.save
      responds_to_parent do
       render :update do |page|
        page << "$('file_uploaded_id').value="+@file.id.to_s
        page.replace_html 'upload_message',"<span class='heading4'>File has been moved to server. Please click submit to upload.</span>"
       end
      end
     else
      responds_to_parent do
       render :update do |page|
        page.replace_html 'upload_message',"<span class='table_commands_row'>Please Upload File</span>"
       end
      end
     end
     rescue Exception=>e
      puts "ERROR :: bulkupload_products :: upload_file :: #{e.to_s}"
      responds_to_parent do
       render :update do |page|
        page.replace_html 'upload_message',"<span class='table_commands_row'>Some internal Error has occurred</span>"
       end
      end
    end
  end
end

Let me know if you have any doubts