2012-03-12 110 views
2

我想知道是否有任何方法来定义索引&索引&的默认respond_to显示在应用程序控制器中的操作,并具有在需要一些定制的其他控制器中重写的能力。如何为应用程序控制器中的index&show动作定义default respond_to?

我认为用一个例子会更容易。

我使用了InheritedResources,CanCan/Authlogic和WickedPDF gems来生成我的PDF和授权用户。我想知道如果我能干掉我的代码。

这里是我有什么

class ProductsController < InheritedResources::Base 
    load_and_authorize_resource 
    respond_to :html, :xml, :json, :pdf 

    def index 
    @products = Product.page(params[:page]) 
    index! do |format| 
     format.pdf do 
     render :pdf => pdf_file_name, 
       :show_as_html => params[:debug].present? 
     end 
    end 
    end 

    def show 
    show! do |format| 
     format.pdf do 
     render :pdf => pdf_file_name, 
       :show_as_html => params[:debug].present? 
     end 
    end 
    end 
end 



class CustomersController < InheritedResources::Base 
    def index 
    index! do |format| 
     format.pdf do 
     render :pdf => pdf_file_name, 
       :show_as_html => params[:debug].present? 
     end 
    end 
    end 

    def show 
    show! do |format| 
     format.pdf do 
     render :pdf => pdf_file_name, 
       :show_as_html => params[:debug].present? 
     end 
    end 
    end 
end 

这一切正常。但是我需要在每个我想生成pdf的控制器中定义format.pdf似乎是多余的。有什么办法可以将它移动到应用程序控制器或指定使用继承资源的地方,然后在每个控制器的基础上覆盖它?有任何想法吗?

谢谢

回答

2

好吧我想出了以下解决方案为其他感兴趣的人。

我想我可以添加一个控制器,继承自InheritedResources,继承自ApplicationController,然后让我的所有其他控制器从它继承(除了一些特殊情况下,将直接从应用程序控制器继承(如HomeController,除了索引之外没有其他任何操作,也没有绑定到任何特定的模型) - 这种方式我可以定义某些默认值 - 我在我的所有控制器中继续使用,如respond_to,并且仍然享受InheritedResources的好处宝石。

class DefaultInheritedResourcesController < InheritedResources::Base 
    # For CanCan authorization - pretty much makes it application wide, without the need 
    # to define it in each controller. Can still override it in ability.rb by making  
    # a resource readable to all users with a session. 
    # if user 
    # can :read, [Product] 
    # end 
    # Also for controllers that need special treatment, you can just inherit from ApplicationController 
    # and override with skip_authorization_check - but for my app it's rare (only HomeController), 
    # most of controllers deal with some kind of resource - so this is a useful convention for 99% of use cases. 

    load_and_authorize_resource 
    respond_to :html, :json, :xml, :pdf 

    # format pdf needs to be redefined on those actions where index! or show! are called. 
    def index 
    super do |format| 
     format.pdf do 
     render :pdf => pdf_file_name, 
       :show_as_html => params[:debug].present? 
     end 
    end 
    end 

    def show 
    super do |format| 
     format.pdf do 
     render :pdf => pdf_file_name, 
       :show_as_html => params[:debug].present? 
     end 
    end 
    end 
end 

然后在我的ProductController的我能做到这一点(注意这里我ProductController的被继承。

class ProductsController < DefaultInheritedResourcesController 
    def index 
    @products = Product.page(params[:page]) 
    super 
    end 
end 

希望这会帮助某人。