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]"
A class is more of a unit, and a module is essentially a loose collection of stuff like functions, variables, or even classes. In a public module, classes in the project have access to the functions and variables of the module.
In Ruby, modules are somewhat similar to classes: they are things that hold methods, just like classes do. However, modules can not be instantiated. I.e., it is not possible to create objects from a module. And modules, unlike classes, therefore do not have a method new .
Modules can contain more than just one class however; functions and any the result of any other Python expression can be globals in a module too. So as a general ballpark guideline: Use classes as blueprints for objects that model your problem domain. Use modules to collect functionality into logical units.
A Module is a collection of methods, constants, and class variables. Modules are defined as a class, but with the module keyword not with class keyword.
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
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