Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Universal Global Function

I would like to expose a global function to all aspects of my Ruby on Rails project (models, views, and controllers). Initially, I thought that I could just add:

def self.my_function
    # Code here...
end

to /config/application.rb and then just call:

Application::my_function

anywhere in my application. But that didn't work. So I did some googling and it appears that I can expose global functions:

  • For my controllers in /app/controllers/application_controller.rb
  • For my views in /app/helpers/application_helper.rb
  • For my models in /lib/

But not for all of them at once.

Can anybody tell me if what I want is possible?

I'd also like to avoid any include statements as much as possible as this is ideally supposed to be accessible from anywhere. But at this point, even using include statements would be OK if I can define the logic for this function in one central location.

like image 209
BlazeCell Avatar asked Mar 08 '13 07:03

BlazeCell


1 Answers

define it in config/environment.rb, before the app gets initialized with:

<YourApp>::Application.initialize!
like image 187
kr1 Avatar answered Sep 29 '22 20:09

kr1