2010-03-22 28 views
2

我正在摔跤,應該很簡單 - 在控制器級別指定一個側欄。隨着佈局,你可以這樣做:在控制器中指定側欄的簡單方法

layout 'admin' 

所以我想這樣做的一個工具,像這樣的東西:

sidebar 'search' 

我知道我可以用content_for在指定欄標記的意見,但我寧願在控制器級別指定側邊欄,而不是重複代碼(並凌亂)我的意見。我也希望能夠在控制器之間共享側邊欄。

目前我已經在初始化得到這個(插件似乎是大材小用了這麼簡單的東西):

module Sidebar 
    def self.included(base) 
    base.extend(ClassMethods) 
    end 

    module ClassMethods 
    def sidebar(partial) 
     # neither of these two work... 
     @sidebar = partial 
     instance_variable_set('@sidebar', partial) 
    end 
    end 
end 

ActionController::Base.send(:include, Sidebar) 

,然後在我的佈局,我想

<%= render "shared/#{@sidebar}" %> 

但無濟於事...

有誰知道我做錯了什麼,或者如果我確實正在做這個正確的方法呢?任何幫助是極大的讚賞!

回答

3

這是範圍問題。該視圖需要一個實例變量,但是您的側邊欄方法在類作用域中起作用。

module Sidebar 
    def self.included(base) 
    base.extend(ClassMethods) 
    end 

    module ClassMethods 
    def sidebar(partial) 
     before_filter do |controller| 
     controller.instance_eval { @sidebar = partial } 
     end 
    end 
    end 
end 

ActionController::Base.send(:include, Sidebar) 

如果所有的控制器包括一個工具,那麼你可以考慮在你的應用程序控制器來定義一個實例變量。

class ApplicationController < ActionController::Base 

    attr_accessor :sidebar 

end 

module Sidebar 
    def self.included(base) 
    base.extend(ClassMethods) 
    end 

    module ClassMethods 
    def sidebar(partial) 
     before_filter do |controller| 
     controller.sidebar = partial 
     end 
    end 
    end 
end 

ActionController::Base.send(:include, Sidebar) 

此外,如果您沒有其他方法,可以進一步簡化您的mixin。

class ApplicationController < ActionController::Base 
    attr_accessor :sidebar 
end 

module Sidebar 
    def sidebar(partial) 
    before_filter do |controller| 
     controller.sidebar = partial 
    end 
    end 
end 

ActionController::Base.extend(Sidebar) 

就我個人而言,我不太喜歡這種方法。我更喜歡在視圖文件中定義邊欄的內容,並且在沒有設置自定義值的情況下回退到標準值。

+0

嗨西蒙娜, 感謝您的回答,這是有道理的。我一直在想它,但我得出的結論是,儘管它可能意味着在控制器的所有視圖中指定相同的側邊欄,但最好在視圖中定義側邊欄並將其作爲默認回退說。 乾杯 Dave – 2010-03-22 14:43:35

相關問題