How to Explore Existing Ruby On Rails Project

=========== How to setup Development Environment =========

STEP -1: Install Ruby with RVM. Use ruby version you are going to use in your project

STEP -2: Clone Project from VCS and Place in your directory and cd to your “project” and ask which branch is ahead and checkout to that branch

STEP -3: If gemset already created then if you cd to project it will automatically use that otherwise create gemset

STEP -4: install bundler by typing this command: ‘gem install bundler’ and install other dependances if require

STEP -5: Type command: ‘bundle install’ to install all gems. In between you will meet with many unmet dependancy errors. Solve them.

STEP -6: Check config/database.yml file and fill reqire information if needed

STEP -7: Type these commands one by one:
rake db:create # to create database, Solve errors if any
rake db:migrate # to migrate all migration to database
rake db:seed # if any seed data

STEP -8: Now type command: ‘rails s’ inside your project directory to start server and visit ‘localhost:3000’ into browser

======== ============ How to Explore Existing Rails Project ==================

1) Use The Site. Understand the purpose of the product

It can be tempting to jump straight in to the code to see how everything works. If the site is already up and hosted somewhere, try and curtail that urge and instead just go use the existing site. Click around and really get a feel for it. Even if you’ve been given an administrator account with which to work on the app, create an account and go through the sign up process. Pay attention to the URLs and paths. This will give you a general idea of the overall flow of the application. Don’t worry about any 500 errors you see, just make a mental note.

2) Read the Gemfile Twice

The Gemfile will contain all of the different external libraries in use by the application. If you’ve been working with Rails apps for a little while, you may be familiar with most of the gems inside. The most subtle surprises that arise when reading a new code base are from external libraries — mystery method definitions and constants that aren’t directly searchable in the application code can be troublesome to locate. You won’t necessarily combat all of those by getting familiar with the library names in the Gemfile but seeing them may jog your memory later.

3) Build a project vocabulary

What is a Player , and what’s a Session ? How about an Account vs a User vs
a Provider ?
Every app uses different terms and differentmetaphors. And if you don’t understand the vocabulary of an app, you’ll waste time browsing app/models every time you see a new class name.Or worse, you’ll make bad assumptions about how features work.So, the first thing you have to do is build that vocabulary. Learn what this app is made of. And if you want to do that quickly, start by reading db/schema.rb . You’ll learn the terms
the app uses, and how all its data fits together. Pay special attention to the *_id columns,
so you can see how the models connect to one another.If you’re more visual, try the rails­erd gem. It generates a diagram from your Rails models,showing all your tables and columns and how they interact. Keep a printout on your desk,and you’ll have an easier time understanding the rest of your app.

After this checkout seed.rb file

4) Check out the models

The app/models directory is the next place to check when going through an app for the first time. I won’t necessarily even open every single model when looking through the code the first time — it’s just good to get vaguely familiar with the models in the app.

In a well­designed Rails app, not everything will be backed by a database table. To continue to build your project vocabulary, look inside app/models for extra classes and attributes that you didn’t see inside db/schema.rb.Don’t spend too much time here yet. It’s easy to get lost in how things work. You’re just here
to fill out your project vocabulary.

 As you learn more about the parts your app is built from, you might wonder why certain
objects exist, or why they fit together the way they do. And that’s the point of the next stage.

5) Helpers and Routes

This is the last stop on the app tour before getting in to the front-end code. The reason for checking the helpers directory first is to get the idea of potential helper routes that may not be covered in the routes.rb file. A lot of apps will create custom helpers for URLs and I’ve noticed it’s beneficial to keep those in mind early. With any luck, common layout code will be extracted in to helpers as well which is also good to know up front.

6) Look at The Controllers

I’ve found it helpful to glance at the ApplicationController first to see what methods are used in every controller in the application. It’s usually a great source of information and can be filled with rescue_from directives which will save you head-aches later. After the ApplicationController, take a look at other controllers in the app and look for similarities:

Do they follow Rails conventions?
Does the app follow a skinny controller/fat model conventions?
Is the app RESTful?
Controllers can be a pain point in Rails applications and you may find some less than ideal code here.

7) Check the lib directory

The lib directory has been, in my experience, the source of most surprises when working on an existing Rails application. Unless the team has had a rigid structure in place, code seems to be dumped in here when it doesn’t fit anywhere else. Random POROs, miscellaneous modules, and more wind up finding a home in the lib directory. You’re not trying to read every file in here but it’s still the first stop I make after the test directory. It’s also where the rake tasks live, so check those out while you’re in here.

8) Asset Pipeline and Related Directories

A quick glance at th app/assets and related directories can give you a bunch of information with a relatively quick glance:

What JavaScript frameworks are being used?
What CSS frameworks are being used?
Are there any other external front-end libraries in use?

9) Try the app, and find out “why”

Once you feel comfortable with the objects the app uses, start the app up. Click around and explore. If there’s documentation, it can help guide you. Otherwise, just see those terms you just learned come to life.
As you use the app, you’ll start to see it from a higher level. You’ll notice that there are reasons why models have the associations they do. Why they’re grouped together. Why those class names were chosen. Maybe they all appear on pages together, or are built from
the same form.And when you start to understand the parts the app is built from and why they exist, you’re
ready to figure out how it all works.

10) Figure out the “how”

By now, you know enough about the app to learn it in detail. You won’t get distracted by new terms and new interactions. You can pick one thing you want to learn, and follow it all the way through.
There are lots of ways you can go from here. These are a few of my favorites:
Browse the UI, and think: How could this feature be built, knowing what you know about the pieces? Can you guess? Use a debugger to confirm your guess, or discover how it actually works.
Pick a test case and follow it all the way through the app. Either read through the code,or explore it with a debugger.Pick a route or controller action. Can you figure out how to reach that controller action from the UI?
This is also a good time to go back through your models and plain Ruby objects. And this time, you cango into the details of how the models work.Become curious about the app. Find gaps in your knowledge and close them with a debugger and the code.

11) Why not start with the tests?

But absolutely, make sure the tests run. If they don’t, you’re working with a broken system. And you can’t rely on the things you discover from a broken system.

================ Conclusion ================

What, to why, to how

To understand a new Rails app, go through these three phases, in this order:

What parts make up this app?

Why do those parts exist? Why are they put together that way?

How does each piece work?

That will give you both the broad point of view and the narrow knowledge you need in order to make that new app yours.


How to Install Sublime in Ubuntu 14.04

There are two version’s of Sublime Text is available to install. Install any one version as per your requirements using following options on Ubuntu and Debian Systems.

Install Sublime Text 2:

$ sudo add-apt-repository ppa:webupd8team/sublime-text-2
$ sudo apt-get update
$ sudo apt-get install sublime-text

Install Sublime Text 3:

$ sudo add-apt-repository ppa:webupd8team/sublime-text-3
$ sudo apt-get update
$ sudo apt-get install sublime-text-installer


If you are coming from a previous version of Rails, you may be wondering why the update action of a RESTful route is mapped to the HTTP verb PATCH instead of PUT. In the HTTP standards document RFC 57892, it outlines that a PUT request to a given resource is meant to completely replace it on the origin server. However, when updating a resource in Rails, rarely, if ever, do you replace an entire resource when performing an update. For example, when updating an Active Record model, Rails sets the attribute updated_at timestamp, not the requesting client.

To follow better HTTP semantics, Rails will be using the HTTP verb PATCH for updates. PATCH allows for both full and partial updates of a resource, and is more suited to how Rails updates resources.If you are upgrading an existing Rails application, the HTTP verb PUT will still map to the update action in
RESTful routes, but it’s recommended to use PATCH moving forward.

Connect to Multiple Databases In Rails

The simple default Rails convention of connecting to one database per appli-cation is suitable most of the time. That’s why its creators made it so easy.But what if you need to step outside the norm and connect to multiple databases? What if, for example, you need to connect to a commercial appli- cation’s tables to integrate your nifty new rich web application with a legacy tool that your company has relied on for years? How do you configure and create those multiple connections? How do you cleanly connect to multiple databases in a single Rails application?
To connect to multiple databases in a Rails application, we’ll set up named
connections in our application’s database configuration, configure our Active
Record models to use it, and use inheritance to safely allow multiple models
to use the new named connection.
To understand how to connect to multiple databases from your Rails applica-
tion, the best place to start is to understand how the default connections are
made. How does an application go from a YAML configuration file to a database
connection? How does an Active Record model know which database to use?
When a Rails application boots, it invokes the Rails initialization process. The
initialization process has the big job of ensuring that all the components of
Rails are properly set up and glued together. In Rails 3 and newer, this process
does its work by delegating to each subframework of Rails and asking that
subframework to initialize itself. Each of these initializers is called a Railtie .
Active Record defines ActiveRecord::Railtie to play the initialization role. One of
its jobs is to initialize database connections.
The Active Record Railtie is responsible for calling the method ActiveRe-
cord::Base.establish_connection() . If you call this method with no arguments, it will
check the value of the Rails.env variable and will look up that value in the
loaded config/database.yml . The default value for Rails.env is development . So, by

By default, on initialization a Rails application discovers which environment it’s
running under (development, test, or production in a stock Rails app) and finds a
database configuration in config/database.yml that is named for the current environment.
Here’s a simple sample:
adapter: mysql2
encoding: utf8
reconnect: false
database: multiple_dbs_development
pool: 5
username: root
socket: /tmp/mysql.sock
adapter: mysql2
encoding: utf8
reconnect: false
database: multiple_dbs_test
pool: 5
username: root
socket: /tmp/mysql.sock
adapter: mysql2
encoding: utf8
reconnect: false
database: multiple_dbs_production
pool: 5
username: root
socket: /tmp/mysql.sock
If you’ve done any database work with Rails, you’ve already seen (and probably con-
figured) a file that looks like this. The naming conventions make it quite obvious what
goes where, so you may find yourself blindly editing this file to achieve the desired
default, if you start a Rails application, it looks up the database configuration
section named development in its config/database.yml file and sets up a connection
to that database.
Note that an actual connection has not yet been established. Active Record
doesn’t actually make the connection until it needs it, which happens on the
first reference to the class’s connection() method. So if you’re following along
and watching open database connections, don’t be surprised if you don’t see
an actual connection made immediately after your application boots.

Having set up a connection to a database solves only part of the puzzle. That
connection still has to be referenced by the model classes that need it. Things
get interesting here. When the default connections are made by the Railtie ,
they are made directly from the ActiveRecord::Base class, which is the superclass
of all Active Record models. Because the call to establish_connection() is made on
ActiveRecord::Base , the connection is associated with the ActiveRecord::Base class
and is made available to all of its child classes (your application-specific
So, in the default case, all your models get access to this default connection.
If you make a connection from one of your model classes (by calling establish_con-
nection() ), that connection is available from that class and any of its children
but not from its superclasses, including ActiveRecord::Base .
When asked for its connection, the behavior of a model is to start with the
exact class the request is made from and work its way up the inheritance
hierarchy until it finds a connection. This is a key point in working with
multiple databases. A model’s connection applies to that model and any of
its children in the hierarchy unless overridden.
Now that we know how Active Record connections work, let’s put our knowl-
edge into action. We’ll contrive a couple of example databases with which to
demonstrate our solution. The following is our config/database.yml file. We have
two databases. One is labeled as development and will be our default database.
The other is labeled products and simulates the hypothetical scenario of having
an existing, external product database for a new application.
adapter: mysql2
encoding: utf8
reconnect: false
database: myrailsdatabase_development
pool: 5
username: root
socket: /tmp/mysql.sock
adapter: mysql2
encoding: utf8
reconnect: false
database: products
pool: 5
username: root
socket: /tmp/mysql.sock

We’ll also create some tables in these databases so we can hook them up to
Active Record models. For our default Rails database, we’ll create a migration
defining tables for users and shopping carts.
class AddUsersAndCarts < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :name
t.string :email
create_table :carts do |t|
t.integer :user_id
create_table :selections do |t|
t.integer :cart_id
t.integer :product_id
In a typical scenario like this, the second database would be one that already
exists, which you wouldn’t want to (or be able to) control via Active Record
migrations. As a result, Active Record’s migrations feature wasn’t designed
to manage multiple databases. That’s OK. If you have that level of control
over your databases and the tables are all related, you’re better off putting
them all together anyway. For this example, we’ll assume that the products
database already has a table called products , with a varchar field for the product
name and a float for the price. For those following along, the following simple
DDL can be used to create this table on a MySQL database:
CREATE TABLE `products` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) default NULL,
`price` float default NULL,
Now that we have our databases set up, we’ll generate models for User , Cart ,
and Product . The User model can have an associated Cart , which can have mul-
tiple Product s in it. The User class is standard Active Record fare:
class User < ActiveRecord::Base
has_one :cart

Things start to get a little tricky with the Cart class. It associates with User in
the usual way. We’d like to use has_many() with a join model to link to :products ,
but we can’t, because our products table is not in the same database. The
has_many() method will result in a table join, which we can’t do across database
connections. Here’s the Cart class without any association with the Product
class Cart < ActiveRecord::Base
Before we deal with hooking Cart s to Product s, let’s look at our Product model:
class Product < ActiveRecord::Base
establish_connection :products
As we learned earlier, Active Record establishes connections in a hierarchical
fashion. When attempting to make a database connection, Active Record
models look for the connection associated with either themselves or the
nearest superclass. So, in the case of the Product class, we’ve set the connection
directly in that class, meaning that when we do database operations with the
Product model, they will use the connection to our configured products database.
If we were to load the Rails console now, we could see that we are indeed
connecting to different databases depending on the model we’re referencing:

>> $ rails console
>> Cart.connection.current_database
=> “myrailsdatabase_development”
>> Product.connection.current_database
Great! Now if we were to call, say, Product.find() , we would be performing our
select against the products database. So, how do we associate a Cart with Product s?
We have many different ways to go about doing this, but I tend to favor the
laziest solution. To make the connection, we’ll create a mapping table in our
application’s default database (the same one the cart table exists in):
class CreateProductReferences < ActiveRecord::Migration
def self.up
create_table :product_references do |t|
t.integer :product_id
def self.down

drop_table :product_references
This table’s sole purpose is to provide a local reference to a product. The
product’s id will be stored in the product reference’s product_id field. We then
create a model for this new table:
class ProductReference < ActiveRecord::Base
belongs_to :product
has_many :selections
has_many :carts, :through => :selections
def name
def price
We’ve created the has_many() relationship between our new ProductReference class
and the Cart class with a join model called Selection , and we’ve associated each
ProductReference with a Product . Here’s the Selection definition:
class Selection < ActiveRecord::Base
belongs_to :cart
belongs_to :product, :class_name => “ProductReference”
Since our Product class is simple, we have also manually delegated calls to
name() and price() to the Product , so for read-only purposes, the product reference
is functionally equivalent to a Product .
All that’s left is to associate the Cart with its products:
class Cart < ActiveRecord::Base
has_many :selections
has_many :products,
:through => :selections
We can now say things such as and get the data
we desire. This solution would, of course, require the necessary rows to be
created in the product_references table to match any products we have in the
alternate database. This could be done either in a batch or automatically at

Now what if you would like to connect to multiple tables in the same external
database? Based on what we’ve done so far, you’d think you could add calls
to establish_connection() in the matching models for each of the new tables. But,
what you might not expect is that this will result in a separate connection for
every model that references your external database. Given a few tables and
a production deployment that load balances across several Rails processes,
this can add up pretty quickly.
Thinking back to what we learned about how database connections are
selected based on class hierarchy, the solution to this problem is to define a
parent class for all the tables that are housed on the same server and then
inherit from that parent class for those external models. For example, to ref-
erence a table called tax_conversions on the products database, we could create a
model called External as follows:
class External < ActiveRecord::Base
self.abstract_class = true
establish_connection :products
Then, our Product and TaxConversion models could inherit from External like so:
class Product < External
class TaxConversion < External
Note that we’ve moved the establish_connection() call from Product to External . All
subclasses of External will use the same connection. We also set abstract_class to
true to tell Active Record that the External class does not have an underlying
database table.

opposed to direct database access. For read-only feeds of data that need to
participate in complex joins, consider replic

Ruby On Rails : Devise Mailer : Customize / Override the Mailer

# app/mailers/my_devise_mailer.rb
class MyDeviseMailer < Devise::Mailer
  helper :application # gives access to all helpers defined within `application_helper`.
  include Devise::Controllers::UrlHelpers # Optional. eg. `confirmation_url`
  default template_path: 'devise/mailer' # to make sure that your mailer uses the devise views

  # Overrides same inside Devise::Mailer
  def confirmation_instructions(record, token, opts={})
    opts[:from] = ''

  # Overrides same inside Devise::Mailer
  def reset_password_instructions(record, token, opts={})
    opts[:from] = ''

  # Overrides same inside Devise::Mailer
  def unlock_instructions(record, token, opts={})
    opts[:from] = ''

After that, change setting in devise.rb file

config.mailer = “MyDeviseMailer”

Don’t forget to restart the server because it is in config

Can we use helper method in controller?


Does anyone know why I get

undefined method `my_method' for #<MyController:0x1043a7410>

when I call my_method(“string”) from within my ApplicationController subclass? My controller looks like

class MyController < ApplicationController
  def show
    @value = my_method(params[:string])

and my helper

module ApplicationHelper
  def my_method(string)
    return string

and finally, ApplicationController

class ApplicationController < ActionController::Base
  after_filter :set_content_type
  helper :all
  helper_method :current_user_session, :current_user
  filter_parameter_logging :password
  protect_from_forgery # See ActionController::RequestForgeryProtection for details


You cannot call helpers from controllers. Your best bet is to create the method in ApplicationController if it needs to be used in multiple controllers.

EDIT: to be clear, I think a lot of the confusion (correct me if I’m wrong) stems from the helper :all call. helper :all really just includes all of your helpers for use under any controller on the view side.

What If you want to use?

Include ApplicationHelper in application_controller.rb file like this:

class ApplicationController < ActionController::Base
  include ApplicationHelper  

This way all the methods defined in application_helper.rb file will be available in the controller.

You can also include individual helpers in individual controllers.