2012-03-12 111 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 

希望這會幫助某人。