Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create global utility functions in rails

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?

like image 664
Matt York Avatar asked Dec 08 '22 21:12

Matt York


2 Answers

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

like image 152
varatis Avatar answered Dec 20 '22 12:12

varatis


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
like image 38
Bill Duckerson Avatar answered Dec 20 '22 12:12

Bill Duckerson