Global functions and variables

Hey People,

I’m fairly new to Rails and have perhaps an obvious question. I would
like
to know if there is a place that I can declare variables and methods
that
are globally available to all controllers. My main reason for this is I
like
to auto generate select boxes based off of the contents of a hash and
would
like to be able to do this in all views in all controllers, so that I do
not
have to repeat either the methods involved or the hashes I’ve created.

Would I accomplish this by just creating a new .rb file and requiring it
in
the environments file, or is there a more standard way to do this. I
know
there are helpers available, but wasn’t sure if they worked globally or
just
for certain views.

Thanks,
~Drew

Excellant, that was exactly what I was looking for. Thanks.

On Tuesday 03 Jan 2006 06:31, Drew B. wrote:

there are helpers available, but wasn’t sure if they worked globally or
just for certain views.

Your application_helper.rb works globally, or for more specific things,
you
can put them in the helpers for your individual classes. All are found
in
your helpers directory.

So for example, I have a boolean select helper in my application.rb to
give
yes/no rather than true/false or a checkbox, since my customer would
prefer
yes/no to true/false throughout the site:

def boolean_select(object, fieldname, options ={})
select(object, fieldname, {“Yes” => true, “No” => false}, options)
end

But then in my booking_helper.rb, I have a title box helper, since that
one
only applies to bookings:

def title_select(object, fieldname, options ={})
select(object, fieldname, %w{Mr Mrs Miss Ms Dr Prof}, options)
end

I’ve included those two examples because they’re hopefully similar to
whatever
you’re trying to do.

For non-view related methods (I have some that clean up strings, used by
multiple models and so on), you can put things in application.rb, or if
it
makes sense to (perhaps you have a lot of related stuff that deserves
it’s
own file), just make another .rb file and include it in application.rb.

As for global variables, I’m not sure, since I’m not using any, but I
guess
you might as well just try putting them in application.rb as well.

There’s also this nice article by Amy Hoy, which might help you:
http://www.slash7.com/articles/2005/03/06/rails-what-goes-where

~Dave

Dave S.
Rent-A-Monkey Website Development
Web: http://www.rentamonkey.com/

On Tuesday 03 Jan 2006 08:11, Dave S. wrote:

So for example, I have a boolean select helper in my application.rb to give
yes/no rather than true/false or a checkbox, since my customer would prefer
yes/no to true/false throughout the site:

Sorry, my bad, that was in application_helper.rb, not application.rb!!

~Dave

Dave S.
Rent-A-Monkey Website Development
Web: http://www.rentamonkey.com/