Rails3 way

37
Amazing things in Rails @ka8725

Transcript of Rails3 way

Page 1: Rails3 way

Amazing things in Rails@ka8725

Page 2: Rails3 way

Load gems precedenceconfig/application.rb:

config.plugins = [:devise, :i18n, :all]

* default precedence is alphabetical

Page 3: Rails3 way

Changing backtraceconfig/initializers/backtrace_silencer.rb:Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }

Rails.backtrace_cleaner.remove_silencers!

Page 4: Rails3 way

List of loaded gems$ rails c>> $LOAD_PATH

=>[“/usr/local/lib/ruby/...”, ...]

Page 5: Rails3 way

Log to syslog

Allows to log to the remote server

http://docs.seattlerb.org/SyslogLogger/

Page 6: Rails3 way

Log to syslogAllows to log to the remote serverhttp://docs.seattlerb.org/SyslogLogger/

Page 7: Rails3 way

Redirecting routes

match ‘/google’, :to => redirect(‘http://google.com’)

config/routes.rb:

Page 8: Rails3 way

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”

Page 9: Rails3 way

List of controller routes$ rake routes CONTROLLER=productsWill show the list of ProductsController routes

Page 10: Rails3 way

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’

Page 11: Rails3 way

Avoid member actions

resources :bids doresource :retractionend

Page 12: Rails3 way

Verify instead of before_filter

verify :params => ‘privileges’, :only => :update, :redirect_to => {:action => ‘settings’}

* Redirects to setting action unless privileges param key presents

Page 13: Rails3 way

Read attributes before type casting

<attribute_name>_before_type_cast

* Example: @user.phone_before_type_cast

Page 14: Rails3 way

Read only attributes

class Customer < ActiveRecord::Baseattr_readonly :social_security_numberend

Page 15: Rails3 way

Get random record

Timesheet.limit(1).offset(rand(Timesheet.count)).first

Page 16: Rails3 way

Select all attributes with calculated values

BilableWeek.select(:*, “mon_hrs + tues_hrs as two_day_total”)

* Pay attention on :*

Page 17: Rails3 way

Method “from” in the selects to join tables or viewsBilableWeek.select(“...”).from(“users”).where(“users.name = ‘John’”)

Page 18: Rails3 way

Method ‘exists?’ in AR

User.exists?(1)

User.find_by_id(1).present?

Page 19: Rails3 way

Use Time instead of DateTime

Time is faster because it is written in C

Page 20: Rails3 way

Redo migration

rake db:migrate:redo

It’s the same as:

rake db:rollbackrake db:migrate

Page 21: Rails3 way

Difference between << and create on the associations<< is transactional, but create is not

<< triggers :before_add and :after_add callbacks but create doesn’t

Page 22: Rails3 way

Method ‘clear’ on the associations

Transactionally removes all records and triggers callbacks

Page 23: Rails3 way

Reloading associations

User.locations(true)

Page 24: Rails3 way

insert_sql and delete_sql options for associations

Convenient way to avoid callbacks

* Please, reference to rails doc

Page 25: Rails3 way

:autosave => true

class User < ARhas_many :timesheets, :autosave => trueend

user = User.firstuser.timesheets.first.mark_for_destrictionuser.save # will delete timesheet record

Page 26: Rails3 way

validates_acceptance_of

Creates virtual attributes automatically

class Account < ARvalidates_acceptance_of :privacy_policy, :terms_of_service

end

Page 27: Rails3 way

validates on

Validators for specific fields

class Report < ARvalidates_presence_of :name, :on => :publishend

report.valid? :publish

Page 28: Rails3 way

Merging scopes

For this purpose you are able to use merge method too

scope :tardy, :lambda {joins(:timesheets).group(“users.id”) & Timesheet.late}

Page 29: Rails3 way

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

Page 30: Rails3 way

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

Page 31: Rails3 way

Calculation methods#average#count#maximum#minimum#sum

Person.calculate(:count, :all)Person.average(:age)Person.minimum(:age).where(‘last_name <> ?’, ‘John’)

Page 32: Rails3 way

STI another column

set_inheritance_column ‘not_type’

Page 33: Rails3 way

Check defined local variables in partials

local_assigns.has_key? :special

Page 34: Rails3 way

Entry counter in the partials

= div_for(entry) dospan ##{entry_counter}span #{entry.name}

Page 35: Rails3 way

Many asset hosts

config.action_controller.asset_host = Proc.new { |source|

“http://assets#{rand(2) + 1}.example.com”}

Page 36: Rails3 way

number_to_phone method

number_to_phone(1235551234) #=> “123-555-1234”

Page 37: Rails3 way

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>