Rails: how to use helpers in a separate class in lib

I happened to write a single file in the lib folder, and I want to use TextHelper in this file. How can I make Texthelper available?

Suggestions appreciated, Thank you,

+5
source share
2 answers

This is actually not so difficult. You can simply enable the module TextHelperfrom your class.

class MyLib
  include ActionView::Helpers::TextHelper

  def five_things(x)
    pluralize 5, x
  end
end

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

This is from class I defined in lib, and the output from the session script/consoleto make sure that all is well.

+6
source

For those whose methods selfdo not seem to inherit functions from the helper, this will work:

class MyLib

  class << self

    include Path::To::YourHelper

    def test_func(x)
      method_in_helper 5, x
    end

  end

end
0
source

All Articles