I need a place to stick global referentially transparent utility methods. These should be accessible from everywhere in rails (Models, Views, Controllers, and everywhere else). e.g.:
bool = GlobalUtilities.to_bool "false"
unicorn = GlobalUtilities.make_me_a "unicorn"
What's the best way to do this?
You could always stick these in /lib
and require them. See bricker's answer -- you can require these modules to be loaded from your application.rb
, which will make them accessible everywhere.
See: Rails lib directory
I would make a descriptively-named file for each behavior that your are hoping to achieve, and collect them in /lib (or, better yet, an engine). Then, mix your desired functionality into the class you hope to extend. For example, in the scenario you described, you could add a parse_boolean
method directly to String
. Pretty slick stuff.
/lib/add_parse_boolean_to_string.rb
class String
def parse_boolean
self == 'true' # or whatever...
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With