Reputation: 19257
I have lots of little utility methods (such as for reformatting or parsing simple objects like strings) I have been putting in ApplicationHelper.
However, ApplicationHelper methods apparently cannot be accessed by class methods in a model.
There is a workaround, which is to sprinkle thoughout my project:
include ApplicationHelper # needed to use apphelper method in instance method
extend ApplicationHelper # needed to use apphelper method in class method
and it seems to work. But it seems like a kludge.
Is there a better place to put utility methods so they can be accessed from anywhere in my project - view, controller method, model instance metho, model class method?
Upvotes: 3
Views: 877
Reputation: 35370
This is what lib/
is for. I have a file at lib/deefour.rb
with
require "deefour/core_ext"
module Deefour; end
I put custom methods in lib/deefour/helpers.rb
module Deefour
module Helpers
extend self
def some_method
# ...
end
end
end
and core monkey patches in lib/deefour/core_ext.rb
class String
def my_custom_string_method(str)
# ...
end
end
In config/initializers/deefour.rb
I put
require "deefour"
In your config/application.rb
make sure you have
config.autoload_paths += Dir["#{config.root}/lib"]
Finally, in ApplicationController
(for controllers), ApplicationHelper
(for views), and wherever else I need it (ie. a specific model here and there) I simply do
include ::Deefour::Helpers
Upvotes: 5