cheatsheets/_deprecated/Rails_2.ctxt

105 lines
2.3 KiB
Plaintext

# Debug
logger.debug "xx"
# Controller stuff
class MyController < ApplicationController::Base
controller.response.body
# Filters
before_filter :require_login # Looks for require_login method
before_filter MyFilter # Looks for MyFilter class
before_filter { |ct| head(400) if ct.params["stop_action"] }
around_filter :catch_exceptions
after_filter :xx
layout "admin_area" # Looks for the view file
layout "admin_area", :except => [ :rss, :whatever ]
layout :foo # Looks for private function foo
private
def whatever ...
class MyFilter
def self.filter(controller, &block)
# Model
belongs_to :user
validates_presence_of :user
default_scope :order => 'id DESC'
named_scope :today, :conditions = "created_at x"
named_scope :today, lambda {{ :conditions = [ "created_at between ? and ?", 1.hour.ago.utc, 300.seconds.ago.utc ] }}
# Then you can call feed.today
# Controller methods
render :action => 'help', :layout => 'help'
render :text => 'so and so'
render :status => :created, :location => post_url(post) # With HTTP headers
redirect_to :action => 'index'
render :partial => 'product', :collection => @products, :as => :item, :spacer_template => "product_ruler"
return head(:method_not_allowed)
head :created, :location => '...'
url_for :controller => 'posts', :action => 'recent'
location = request.env["SERVER_ADDR"]
# For views
auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "RSS Feed"})
javascript_include_tag "foo"
stylesheet_link_tag
image_tag
# Ruby stuff!
# Defining a class method (not a typo)
Fixnum.instance_eval { def ten; 10; end }
Fixnum.ten # => 10
# Defining an instance method
Fixnum.class_eval { def number; self; end }
7.number #=> 7
# Multiple arguments, send()
class Klass
def hello(*args); "Hello " + args.join(' '); end
end
Klass.new.send :hello, "gentle", "readers"
def can(*args)
yield if can?(*args)
end
# can(x) {...} => if can?(x) {...}
# Struct
class Foo < Struct.new(:name, :email)
end
j = Foo.new("Jason", "jason@bateman.com")
j.name = "Hi"
print j.name
# Struct
class Foo < Struct.new(:name, :email)
end
j = Foo.new("Jason", "jason@bateman.com")
j.name = "Hi"
print j.name
# Method missing
def method_missing(method_name, *arguments)
if method_name.to_s[-1,1] == "?"
self == method_name.to_s[0..-2]
# Rails logger
Rails.logger.info("...")
# To string
:hello_there.to_s