简体   繁体   中英

Rails: How do I use helpers in a separate class in lib

I'm happened to write create one file in lib folder and I want to use TextHelper in that file. How can I make Texthelper available?

Suggestions appreciated, Thanks,

Actually it's not that hard at all. You can just include the TextHelper module from your class.

class MyLib
  include ActionView::Helpers::TextHelper

  def five_things(x)
    pluralize 5, x
  end
end

>> MyLib.new.five_things "dog"
=> "5 dogs"

That's from a class I defined in lib , and output from a script/console session to make sure it all plays nice.

For those whom the self methods don't seem to inherit the functions from helper, this will work:

class MyLib

  class << self

    include Path::To::YourHelper

    def test_func(x)
      method_in_helper 5, x
    end

  end

end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM