Where to define global functions and classes?


#1

Where or how should I define functions and classes to be globally
available to my entire Rails application? When I use script/generate
to make a new model, it is available to to entire app… what if I want
to make a simple class or global func to be available to the entire
app? Is there a specific Rails way to do it?

Thanks.


#2

(answer from beginner)

But if you ask me you should put it in the /app/application.rb to make
it available to all.


#3

(from another beginner)

I had a similar question earlier and the answer was to store methods
callable from views in app\helpers\application_helper.rb and to store
methods that can be called from controllers in
lib\whatever_you_want_to_call_it.rb.

Shauna


#4

what if I want
to make a simple class or global func to be available to the entire
app? Is there a specific Rails way to do it?
It depends on where you need to use this code.

If it’s a view method, helpers/application_helper.rb is the place.

If you have a class that is used by other code then you need to put
that into lib/. For example, if you had a class that encrypts data,
you might create a class called ‘Encryptor’ and put it in
lib/encryptor.rb. If you’re using <Rails 1.2, then you need to add an
include to config/environment.rb to pull that class in. As of Rails
1.2, this is done for you when the class is called.

If you have a method that is used by all controllers, then you can
put it in application_controller.rb, but you should think about whether
it belongs there or should really be in a helper or separate utility
class.

Hope that helps,

Steve


#5

Steve,
Thanks for the reply, that answered my question as well as some others.
Let me see if I got it straight though…

  • Putting methods in module ApplicationHelper found in
    helpers/application_helper.rb will only be available to views (but not
    controllers or models)?
  • files created in /lib will automatically be included in Rails 1.2
    and must be manually included in config/environment.rb in Rails < 1.2?
  • Putting methods in class ApplicationController found in
    controllers/application.rb will be available to all controllers (but
    not views or models)?

Does it sound like I got it?

Thanks,
– C