将方法委派给ApplicationHelper中具有相同名称的类方法



所以我要做的是将format_text方法委托给类级方法,这样我就不会有两个同名的方法。有好的模式或方法吗?这样做的原因是,我可以在视图和演示者中调用format_text。我意识到在视图之外使用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

您可以为其使用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")

最新更新