What is the simplest way to make a group of methods available to several Rails applications
tl;dr
What's a simple way I can create a view helpers module I can use in many apps?
What file, located where, loaded how?
I'm on Rails 2.3.11.
I have a bunch of view helper methods. Here's an example of one of them:
# Render form input fields to add or edit a ZIP code.
def render_zip_code_fields( model_instance )
# Bla bla bla ...
end
I have about 20 or so that I've developed over the years and often use in various applications. I'd like to wrap them all up in one file that I can just drop into and app and then be able to call them in my views.
Why not just copy-and-paste them into application_helper.rb
? That just doesn't feel right to开发者_如何学Go me. It seems like it should be a separate file.
In fact I tried creating in /lib
...
# /lib/my_view_helpers.rb
module MyViewHelpers
# ...
end
And then in application_helper.rb
I put...
include MyViewHelpers
But I got a lot of "uninitialized constant MyViewHelpers errors. Maybe a syntax error? I don't think I need to require
my_view_helpers.rb
first because it's in /lib
. Everything in there gets loaded automatically, right?
So what's the right way to do this optimizing for simplicity?
Sorry this is so long. I get verbose when I'm tired.
As of Rails 3, /lib
is no longer on the default load path. You will need to put the following line in the Application
class in config/application.rb
.
config.autoload_paths += ["#{config.root}/lib"]
An alternative would be to drop the file in app/helpers
since it is a helper, after all.
精彩评论