ºÝºÝߣ

ºÝºÝߣShare a Scribd company logo
Amazing things in Rails
@ka8725
Load gems precedence
config/application.rb:
config.plugins = [:devise, :i18n, :all]




* default precedence is alphabetical
Changing backtrace
config/initializers/backtrace_silencer.rb:
Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
Rails.backtrace_cleaner.remove_silencers!
List of loaded gems
$ rails c
>> $LOAD_PATH
=>[¡°/usr/local/lib/ruby/...¡±, ...]
Log to syslog

Allows to log to the remote server

http://docs.seattlerb.org/SyslogLogger/
Log to syslog
Allows to log to the remote server
http://docs.seattlerb.org/SyslogLogger/
Redirecting routes
config/routes.rb:
match ¡®/google¡¯, :to => redirect(¡®http://google.com¡¯)
Collect complicated routes
config/routes.rb:
match ¡®items/list/*specs¡¯, :controller => ¡®items¡¯, :action => ¡®list¡¯

/items/list/base/books/fiction/dickens/little_dorrit

params[:specs] # => ¡°base/books/fiction/dickens/little_dorrit¡±
List of controller routes
$ rake routes CONTROLLER=products
Will show the list of ProductsController routes
Preview new record route
resources :reports do
new do
     post :preview
end
end

preview_new_report POST /reports/new/preview(.:format) {:action => ¡®preview¡¯,
:controller => ¡®reports¡¯}


= form_for(report, :url => preview_new_report_path) do |f|
...
= f.submit ¡®Preview¡¯
Avoid member actions
resources :bids do
resource :retraction
end
Verify instead of before_filter

verify :params => ¡®privileges¡¯, :only => :update, :redirect_to => {:action => ¡®settings¡¯}




* Redirects to setting action unless privileges param key presents
Read attributes before type
casting
<attribute_name>_before_type_cast




* Example: @user.phone_before_type_cast
Read only attributes
class Customer < ActiveRecord::Base
attr_readonly :social_security_number
end
Get random record

Timesheet.limit(1).offset(rand(Timesheet.count)).first
Select all attributes with
calculated values
BilableWeek.select(:*, ¡°mon_hrs + tues_hrs as two_day_total¡±)




* Pay attention on :*
Method ¡°from¡± in the selects
to join tables or views
BilableWeek.select(¡°...¡±).from(¡°users¡±).where(¡°users.name = ¡®John¡¯¡±)
Method ¡®exists?¡¯ in AR

User.exists?(1)

User.find_by_id(1).present?
Use Time instead of DateTime

Time is faster because it is written in C
Redo migration

rake db:migrate:redo


It¡¯s the same as:

rake db:rollback
rake db:migrate
Difference between << and
create on the associations
<< is transactional, but create is not
<< triggers :before_add and :after_add callbacks but create
doesn¡¯t
Method ¡®clear¡¯ on the
associations
Transactionally removes all records and triggers callbacks
Reloading associations

User.locations(true)
insert_sql and delete_sql
options for associations
Convenient way to avoid callbacks




* Please, reference to rails doc
:autosave => true

class User < AR
has_many :timesheets, :autosave => true
end

user = User.first
user.timesheets.first.mark_for_destriction
user.save # will delete timesheet record
validates_acceptance_of

 class Account < AR
   validates_acceptance_of :privacy_policy, :terms_of_service
 end



Creates virtual attributes automatically
validates on
class Report < AR
validates_presence_of :name, :on => :publish
end

report.valid? :publish




Validators for specific fields
Merging scopes

scope :tardy, :lambda {
joins(:timesheets).group(¡°users.id¡±) & Timesheet.late
}




For this purpose you are able to use merge method too
Callback classes
class MarkAsDeleted
  def self.before_destroy(model)
    model.update_attribute(:deleted_at, Time.now)
    false
  end
end

class Account < AR
  before_destroy MarkAsDeleted
end

class Invoice < AR
  before_destroy MarkAsDeleted
end
Callback classes
class MarkAsDeleted
  def self.before_destroy(model)
    model.update_attribute(:deleted_at, Time.now)
    false
  end
end

class Account < AR
  before_destroy MarkAsDeleted
end

class Invoice < AR
  before_destroy MarkAsDeleted
end
Calculation methods
#average
#count
#maximum
#minimum
#sum

Person.calculate(:count, :all)
Person.average(:age)
Person.minimum(:age).where(¡®last_name <> ?¡¯, ¡®John¡¯)
STI another column



set_inheritance_column ¡®²Ô´Ç³Ù³å³Ù²â±è±ð¡¯
Check defined local variables in
partials


local_assigns.has_key? :special
Entry counter in the partials


= div_for(entry) do
  span ##{entry_counter}
  span #{entry.name}
Many asset hosts


 config.action_controller.asset_host = Proc.new { |source|
   ¡°http://assets#{rand(2) + 1}.example.com¡±
 }
number_to_phone method



 number_to_phone(1235551234) #=> ¡°123-555-1234¡±
auto_link method

 auto_link(¡°Go to http://google.com. Email:
 test@email.com¡±)

 => Go to <a
 href=¡±http://google.com¡±>http://google.com</a>. Email: <a
 href=¡±mailto:test@email.com¡±>text@email.com</a>

More Related Content

Rails3 way