views:

81

answers:

2

I'm trying to add a function that will be accessible throughout all parts of my program. I want something like:

def GlobalFunctions.my_function(x,y)
    puts x + y
end

to be accessible for all models. Specifically I am trying to use a function like this in my seeds.rb file but I am most likely going to be reusing the code and don't want any redundancy. Now I know I can make a simple class, but I could also make a module. What are some reasons to go in either direction? And once I've decided on which type to use, how do I make it accessible throughout the whole program?

I have tried a module, but I keep getting " Expected app/[module file] to define [ModuleName]"

+1  A: 

You'd define a class for something you'll want to make instances of. In this case, a module would probably be better, as modules basically just group code together:

module GlobalFunctions
  def self.my_function(x,y)
    puts x+y
  end
end

GlobalFunctions.my_function(4,5) # => 9

Alternatively, you could define it on Kernel, and then just call it anywhere. Kernel is where methods like puts are defined.

def Kernel.my_function(x,y)
  puts x + y
end

my_function(4,5) # => 9
PreciousBodilyFluids
Thanks a lot!!!
Jack
A: 

PreciousBodilyFluids is correct, and if this GlobalFunctions is part of a RoR project, you may want to name the file global_functions.rb and place it in the lib/ directory to help you avoid the error message you posted at the end of your question.