SlideShare 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 ‘not_type’
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

PDF
Rails3 changesets
PPTX
Using the Features API
PDF
Spring boot
PDF
Workshop 23: ReactJS, React & Redux testing
PDF
1時間で作るマッシュアップサービス(関西版)
PDF
Rest with-spray
PDF
Angular promises and http
PDF
Server Side? Swift
Rails3 changesets
Using the Features API
Spring boot
Workshop 23: ReactJS, React & Redux testing
1時間で作るマッシュアップサービス(関西版)
Rest with-spray
Angular promises and http
Server Side? Swift

What's hot (20)

PDF
Workshop 26: React Native - The Native Side
PDF
Binary Studio Academy 2016: Laravel Controllers
DOCX
getSIDUsers
PDF
Simple acl with laravel
PDF
Intro to Rails
ODP
Migration from Rails2 to Rails3
PDF
How to replace rails asset pipeline with webpack?
TXT
fabfile.py
PDF
Codeigniter : Custom Routing - Manipulate Uri
PPTX
RESTful Web Development with CakePHP
PDF
OSC2007-niigata - mashup
PDF
Curing Webpack Cancer
DOCX
Laravel
DOCX
MVest Spring Job Execution
PDF
Swift Delhi: Practical POP
PDF
XamarinとAWSをつないでみた話
PDF
Workshop 22: React-Redux Middleware
PDF
Power shell examples_v4
PDF
Protocol-Oriented MVVM (extended edition)
PDF
Introduction to AngularJS For WordPress Developers
Workshop 26: React Native - The Native Side
Binary Studio Academy 2016: Laravel Controllers
getSIDUsers
Simple acl with laravel
Intro to Rails
Migration from Rails2 to Rails3
How to replace rails asset pipeline with webpack?
fabfile.py
Codeigniter : Custom Routing - Manipulate Uri
RESTful Web Development with CakePHP
OSC2007-niigata - mashup
Curing Webpack Cancer
Laravel
MVest Spring Job Execution
Swift Delhi: Practical POP
XamarinとAWSをつないでみた話
Workshop 22: React-Redux Middleware
Power shell examples_v4
Protocol-Oriented MVVM (extended edition)
Introduction to AngularJS For WordPress Developers
Ad

Viewers also liked (18)

PPTX
Presentation147to158
PPTX
Evaluation question 2
PDF
Baa adab baa muhaawara hoshiyaar ( Urdu humor) طنز ومزاح
PPTX
Location shots
PPTX
Basic format robeertaaa carrillooo5656767897890
PPTX
PPTX
Question 2 from evaluation
PDF
Ruby exceptions
PPTX
Question 7 from evaluation
PDF
Корпоративное приложение на Rails
PPTX
Basic format robeertaaa carrillooo5656767897890
PDF
Rails 3 assets pipeline
PPTX
Живые обои для Android. Как создать. Тонкости. Продвижение
PDF
Complete ruby code
PPTX
Atlas an overview sept2012
PDF
Atlas an overview sept2012
PDF
Atlas - An Overview
PPTX
Food security bill
Presentation147to158
Evaluation question 2
Baa adab baa muhaawara hoshiyaar ( Urdu humor) طنز ومزاح
Location shots
Basic format robeertaaa carrillooo5656767897890
Question 2 from evaluation
Ruby exceptions
Question 7 from evaluation
Корпоративное приложение на Rails
Basic format robeertaaa carrillooo5656767897890
Rails 3 assets pipeline
Живые обои для Android. Как создать. Тонкости. Продвижение
Complete ruby code
Atlas an overview sept2012
Atlas an overview sept2012
Atlas - An Overview
Food security bill
Ad

Similar to Rails3 way (20)

PDF
Rails 4.0
PDF
Rails 3 overview
PPT
Rails Page Caching
PDF
Rails 3: Dashing to the Finish
KEY
More to RoC weibo
PDF
Play vs Rails
PDF
Ruby on Rails Security Updated (Rails 3) at RailsWayCon
PDF
All I Need to Know I Learned by Writing My Own Web Framework
PPT
Deploy Rails Application by Capistrano
PPTX
Intro to Rails 4
PDF
How to disassemble one monster app into an ecosystem of 30
PDF
Perl web frameworks
PDF
Curscatalyst
PPT
GHC Participant Training
PDF
浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編
PDF
Flex With Rubyamf
PDF
Integrating Flex And Rails With Ruby Amf
ODP
Ruby on rails
PPT
Effecient javascript
PDF
Design Summit - Rails 4 Migration - Aaron Patterson
Rails 4.0
Rails 3 overview
Rails Page Caching
Rails 3: Dashing to the Finish
More to RoC weibo
Play vs Rails
Ruby on Rails Security Updated (Rails 3) at RailsWayCon
All I Need to Know I Learned by Writing My Own Web Framework
Deploy Rails Application by Capistrano
Intro to Rails 4
How to disassemble one monster app into an ecosystem of 30
Perl web frameworks
Curscatalyst
GHC Participant Training
浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編
Flex With Rubyamf
Integrating Flex And Rails With Ruby Amf
Ruby on rails
Effecient javascript
Design Summit - Rails 4 Migration - Aaron Patterson

Rails3 way