2014-10-20 43 views
2

所以我想要做的是將format_text方法委託給類級方法,這樣我就不會有兩個名稱相同的方法。有沒有一個好的模式或方法來做到這一點?這樣做的原因是,我可以在視圖和演示者中撥打format_text。我意識到在視圖之外使用ApplicationHelper可能不是好習慣。將方法委託給ApplicationHelper中的同名方法

application_helper.rb

module ApplicationHelper 

    # would like to do something like this: 
    # delegate :format_text, to: self.format_text 

    # all this method does is call self.format_text 
    def format_text(text) 
    # calls the class level method 
    format_text(text) 
    end 

    # need the self. in front to use outside of view 
    def self.format_text(text) 
    # do something to the text and return a string 
    end 
end 

視圖使用助手這樣:

some_view.html.haml

%label= format_text('something needs formatting') 

但在某些情況下,格式必須下來的主講人級別。在這種情況下,使用方法format_text它必須被稱爲ApplicationHelper.format_text

some_presenter.rb

def header_of_some_data 
    "#{@name} blah #{ApplicationHelper.format_text('some text')}" 
end 

回答

0

可以使用module_function它:

module ApplicationHelper 
    def format_text(text) 
    # do something to the text and return a string 
    end 
    module_function :format_text 
end 

ApplicationHelper.format_text("text")