Adapted from Brian Luczkiewicz’s 2005-05-04 email to the Rails ML.
For something you need in all your models, make a file and stick it in lib. Put your functions in a module. Require it in config/environment.rb, then open up \ActiveRecord::Base and include the module. Alternatively you could just include the module directly in all of your models, but this is 1-N and could be a maintenance pain.
(Another option is to introduce a subclass of \ActiveRecord:Base and implement the methods there. Then all your models can extend that subclass.)
For a method you need in all controllers, put it in app/controllers/application.rb in the ApplicationController class.
For a method you need in all views, put it in app/helpers/application_helper.rb.
For a method you need in all controllers and views, put it in app/controllers/application.rb and mark it with the helper_method macro.
For a helper method that is relevant to only one view, put it in app/helpers/viewname_helper.rb.
For a helper-type method that is needed by only one controller, put it in the controller and make it non-public. (This should rarely be needed. Consider adding methods to the model instead.)
Anything in lib/ can be required in config/environment.rb directly and you’ll have access to it. It’s best to wrap your functions in modules to keep your namespace clean.
Some of this might be difficult to understand if you’re new to Ruby. Don’t hesitate to ask for help on the mailing list or IRC.
category: Understanding
Adapted from Brian Luczkiewicz’s 2005-05-04 email to the Rails ML.
For something you need in all your models, make a file and stick it in lib. Put your functions in a module. Require it in config/environment.rb, then open up \ActiveRecord::Base and include the module. Alternatively you could just include the module directly in all of your models, but this is 1-N and could be a maintenance pain.
(Another option is to introduce a subclass of \ActiveRecord:Base and implement the methods there. Then all your models can extend that subclass.)
For a method you need in all controllers, put it in app/controllers/application.rb in the ApplicationController class.
For a method you need in all views, put it in app/helpers/application_helper.rb.
For a method you need in all controllers and views, put it in app/controllers/application.rb and mark it with the helper_method macro.
For a helper method that is relevant to only one view, put it in app/helpers/viewname_helper.rb.
For a helper-type method that is needed by only one controller, put it in the controller and make it non-public. (This should rarely be needed. Consider adding methods to the model instead.)
Anything in lib/ can be required in config/environment.rb directly and you’ll have access to it. It’s best to wrap your functions in modules to keep your namespace clean.
Some of this might be difficult to understand if you’re new to Ruby. Don’t hesitate to ask for help on the mailing list or IRC.
category: Understanding