Forum: Ruby on Rails where to define global functions and classes?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Christopher J. Bottaro (Guest)
on 2007-01-19 17:31
(Received via mailing list)
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.
Petar (Guest)
on 2007-01-19 17:31
(Received via mailing list)
(answer from beginner)

But if you ask me you should put it in the /app/application.rb to make
it available to all.
Shauna (Guest)
on 2007-01-20 03:10
(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
Christopher J. Bottaro (Guest)
on 2007-09-26 00:37
(Received via mailing list)
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
Stephen B. (Guest)
on 2007-09-26 00:37
(Received via mailing list)
> 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
This topic is locked and can not be replied to.