Rails3 way
Transcript of Rails3 way
Amazing things in Rails@ka8725
Load gems precedenceconfig/application.rb:
config.plugins = [:devise, :i18n, :all]
* default precedence is alphabetical
Changing backtraceconfig/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 syslogAllows to log to the remote serverhttp://docs.seattlerb.org/SyslogLogger/
Redirecting routes
match ‘/google’, :to => redirect(‘http://google.com’)
config/routes.rb:
Collect complicated routesmatch ‘items/list/*specs’, :controller => ‘items’, :action => ‘list’
config/routes.rb:
/items/list/base/books/fiction/dickens/little_dorrit
params[:specs] # => “base/books/fiction/dickens/little_dorrit”
List of controller routes$ rake routes CONTROLLER=productsWill show the list of ProductsController routes
Preview new record routeresources :reports donew do
post :previewendend
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 doresource :retractionend
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::Baseattr_readonly :social_security_numberend
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 viewsBilableWeek.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:rollbackrake 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 < ARhas_many :timesheets, :autosave => trueend
user = User.firstuser.timesheets.first.mark_for_destrictionuser.save # will delete timesheet record
validates_acceptance_of
Creates virtual attributes automatically
class Account < ARvalidates_acceptance_of :privacy_policy, :terms_of_service
end
validates on
Validators for specific fields
class Report < ARvalidates_presence_of :name, :on => :publishend
report.valid? :publish
Merging scopes
For this purpose you are able to use merge method too
scope :tardy, :lambda {joins(:timesheets).group(“users.id”) & Timesheet.late}
Callback classesclass MarkAsDeleted
def self.before_destroy(model)model.update_attribute(:deleted_at, Time.now)false
endend
class Account < ARbefore_destroy MarkAsDeleted
end
class Invoice < ARbefore_destroy MarkAsDeleted
end
Callback classesclass MarkAsDeleted
def self.before_destroy(model)model.update_attribute(:deleted_at, Time.now)false
endend
class Account < ARbefore_destroy MarkAsDeleted
end
class Invoice < ARbefore_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 ‘not_type’
Check defined local variables in partials
local_assigns.has_key? :special
Entry counter in the partials
= div_for(entry) dospan ##{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: [email protected]”)
=> Go to <a href=”http://google.com”>http://google.com</a>. Email: <a href=”mailto:[email protected]”>[email protected]</a>