Sophy
Sophy

Reputation: 411

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,

Upvotes: 6

Views: 6793

Answers (2)

Prabhjot Singh Rai
Prabhjot Singh Rai

Reputation: 2545

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

Upvotes: 1

Ian Terrell
Ian Terrell

Reputation: 10876

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.

Upvotes: 6

Related Questions