Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Modules vs. Classes

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]"

like image 308
JackCA Avatar asked Mar 11 '10 18:03

JackCA


People also ask

What is the difference between module and class?

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.

Are modules classes Ruby?

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 .

Should I use class or module?

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.

What are modules in Ruby on Rails?

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.


1 Answers

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
like image 106
PreciousBodilyFluids Avatar answered Sep 28 '22 10:09

PreciousBodilyFluids