代码改变世界

Rails2的部分新特性

2008-12-27 00:47  敏捷的水  阅读(484)  评论(0编辑  收藏  举报

1.Action Pack: Resources

map.namespace(:admin) do |admin|  

  admin.resources :products,  

    :collection => { :inventory => :get },  

    :member     => { :duplicate => :post },  

    :has_many   => [ :tags, :images, :variants ]  

end 

image image

2. Action Pack: HTTP Loving

class PostsController < ApplicationController  

  USER_NAME, PASSWORD = "dhh", "secret" 

  before_filter :authenticate, :except => [ :index ]    

  def index  

    render :text => "Everyone can see me!"   

  end 

  def edit  

    render :text => "I'm only accessible if you know the password"   

  end 

  private  

    def authenticate  

      authenticate_or_request_with_http_basic do |user_name, password|   

        user_name == USER_NAME && password == PASSWORD  

      end 

    end 

end 

3. Action Pack: Exception handling

大多数常见的异常都可以统一处理,而不是每个需要单独的处理。通常情况下,你只需要覆盖rescue_action_in_public方法,来进行统一的异常处理即可。但是你也有可能需要使用自己的case语句来处理特定场合的异常。因此我们现在提供了一个类级别的宏叫做rescue_from,你可以使用它来声明针对某个特定的Action来捕获异常

class PostsController < ApplicationController  

  rescue_from User::NotAuthorized, :with => :deny_access 

  protected  

    def deny_access  

      ...  

    end 

end