Ruby/Rails notes

# Use "" to log debug message directly into Ruby/Rails development.log file: "New post: #{@post.attributes.inspect}"

config.log_level is set to "info" for production.rb. So use to get log messages from heroku:
    heroku logs --source app -t

# Use "debugger" to brake into debugger from any where in code:

  def new
    debugger  # Launches debugger shell
    @person =

Note: sudo gem install ruby-debug  # to run the server in debugger mode

# Re-generate "Gemfile.lock"

Gemfile.lock is generated/updated after  re-installing your dependencies using "bundle install". So after modifying Gemfile first do "bundle install", then run "git add" and then "git push heroku".

# Argument Safety

This code is highly preferable:
    Client.where("orders_count = ?", params[:orders])
to this code:
    Client.where("orders_count = #{params[:orders]}")

The actual query could change due to textual replacement if a user, inadvertently or otherwise, sets params[:orders] to things other than the intended orders_count..

# Modules - Library

# trig.rb file
module Trig
   PI = 3.141592654
   def Trig.sin(x)
   # ..

# app.rb file
require 'trig.rb'          # "require" is similar to the #include statement of C
y = Trig.sin(Trig::PI/4)

# Modules - Mixin (similar to multiple inheritance)

# a.rb file
module A
   def a1

# b.rb file
module B
   def b1

# sample.rb file
class Sample
include A
            # "inclide" embeds a module in a class
include B
   def s1

# Delayed Job - asynchronously executing longer tasks in the background

# launch web process as usual:
rails server
# start delayed job (as daemon)
./script/delayed_job start
# ./script/delayed_job stop; ./script/delayed_job start ; tail -f log/delayed_job.log

    # To start worker(s). Note: Procfile can launch both web and worker
    foreman start

# Delete all pending jobs
heroku run console
Delayed::Job.find(:all).each do |dj|

# Scope

In active record, all query building methods (like where, order, joins, limit and so forth) return a so called scope. Only when you call a kicker method like .all, .count, .each or .first the built-up query is executed and the results from the database are returned.

# Removing foreign key reference "user_id" and other unwanted "qty" from table


    class RemoveUserDetailsFromStatuses < ActiveRecord::Migration
      def up
        remove_index :statuses, :user_id
        change_table :statuses do |t|
          t.remove :qty
          t.remove_references :user

      def down
        change_table :statuses do |t|
          t.references :user
          t.integer :qty
        add_index :statuses, :user_id

Note: The sequence of remove_index and remove_references is important.

# Generating select2 tags (selection options) list at runtime

    placeholder: "e3",
    tags:["red", "green", "blue"],
    tokenSeparators: [","]

    placeholder: "e5",
    tags: $("#e5").data("tags"),
    tokenSeparators: [","],
  $("#e5").on("change", function(e) { $("#abcscript_name").val(e.val); });

  <%= text_field_tag :name_list,,
    :id => "e5", :placeholder => "Enter/Select Type",

    :multiple => true, :style => "width:300px",
    :data => { :tags => @selectable_types } %>
  <%= f.text_field :name, {:type => "hidden"} %>

  # @selectable_types = ["One", "Two", "Three"]
  @selectable_types = get_selectable_types
  def get_selectable_types
    # return regular array object, so that it can be used in the view. {|abcscript| abcscript.notes }

# Using Rails Debugger in Eclipse

- Comment a conflicting gem from Gemfile:
  #gem 'ruby-debug19', :require => 'ruby-debug'  # conflicts with Aptina Eclipse Debugger
- If "rails server" is running kill it.
- In Project View, Right click on the project and select "Debug Server"
    Console windows shows a message that server is launched.
- To stop the Debug Server, in Debug Perspective View -> Console -> Terminate.

# Thin Views & Controllers

Keep Views & Controllers "thin", and put most of the code in Model. This makes it easy to do Service Oriented Architecture (SOA).

# Useful gems

cancan: Simple Authorization plugin. More details:

Delayed Job: Database based asynchronously priority queue system to execute longer tasks in background. More details: Elsewhere on this page.

nokogiri: HTML Parsing. More details:

pdf-reader: PDF File reader. More details:,

select2: jQuery based (replacement of) select boxes. Multiple selections, with facility to add new "tags" at runtime. More details: and elsewhere on this page.

# Useful URLs/References

Ruby, Rails, Guide, Reference, Getting Started, API Documentation:
Tutorials & Screencasts:,
HTML CSS Color Code Names:
Haml Pros & Cons:
Closures Examples (lambda):
jQuery, Ajax:,

No comments:

Post a Comment