Ruby/Rails notes

# Use "logger.info" to log debug message directly into Ruby/Rails development.log file:

    logger.info "New post: #{@post.attributes.inspect}"

config.log_level is set to "info" for production.rb. So use logger.info 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 = Person.new
  end



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)
   # ..
   end

end
# 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
   end
end


# b.rb file
module B
   def b1
   end
end


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

samp=Sample.new
samp.a1
samp.b1
samp.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

(Or,
    # 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|
  dj.destroy
end


https://github.com/collectiveidea/delayed_job
https://devcenter.heroku.com/articles/delayed-job


# 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.
db/migrate/


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

db/migrate/ModUserDetails.rb:

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

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

Note: The sequence of remove_index and remove_references is important.


# Generating select2 tags (selection options) list at runtime

script:
  $("#e3").select2({
    placeholder: "e3",
    tags:["red", "green", "blue"],
    tokenSeparators: [","]
  });

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

html:
  <%= text_field_tag :name_list, @abcscript.name,
    :id => "e5", :placeholder => "Enter/Select Type",

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


controller:
  # @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.select(:notes).uniq.collect {|abcscript| abcscript.notes }
  end



# 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: http://railscasts.com/episodes/192-authorization-with-cancan?view=asciicast

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: http://ruby.bastardsbook.com/chapters/html-parsing/

pdf-reader: PDF File reader. More details: https://github.com/yob/pdf-reader, https://rubygems.org/gems/pdf-reader

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


# Useful URLs/References

Ruby, Rails, Guide, Reference, Getting Started, API Documentation: http://apidock.com/rails
Tutorials & Screencasts: http://railscasts.com, http://ruby.railstutorial.org
HTML CSS Color Code Names: http://www.w3schools.com/cssref/css_colornames.asp
Haml Pros & Cons: http://chriseppstein.github.com/blog/2010/02/08/haml-sucks-for-content/
Closures Examples (lambda): http://www.randomhacks.net/articles/2007/02/01/some-useful-closures-in-ruby
jQuery, Ajax: http://api.jquery.com/, http://www.slideshare.net/remy.sharp/prototype-jquery-going-from-one-to-the-other

No comments:

Post a Comment