Blog

a short story about ruby modules and classes

a short story about ruby modules and classes

Whats the difference between modules and classes in ruby? This is a good question, and rails beginners often miss the point. In this blogpost I do not want to explain the explicit difference between modules and classes.

For detailed information just check out these links or google a bit :-).

I want to explain how you could manage the following structure in a pure ruby project:

  • lib
    • foo.rb
    • foo
      • other_foo.rb
      • next_foo.rb

Imagine you have a rails project with a similar structure like this:

  • models
    • foo.rb
    • foo
      • other_foo.rb
      • next_foo.rb

Here you can simple define models like that:

class Foo < ActiveRecord::Base
end

class Foo::OtherFoo < Foo
end

class Foo::NextFoo < Foo
end

Rails handels the requirement and loading in a different way than Ruby does it. Rails extens the Ruby functionallity.

In a pure Ruby project you can implement the structure in the following way:


require "other_foo"
class Foo
end

require "next_foo"
class Foo
  class OtherFoo
  end
end

require "foo"
class Foo
  class NextFoo
  end
end

You can also work with modules:

require "other_foo"
module Foo
end

require "next_foo"
module Foo
  module OtherFoo
  end
end

require "foo"
class Foo
  module NextFoo
  end
end

It depends from your needs, with which style you work with.

But you cannot mix up modules and classes, if you are using the folder structure from above! Otherwise you will get following error:
foo.rb:3:in `': Foo is not a class (TypeError)

This should just be a short insight into the topic Rails vs. Ruby Module vs. Class loading and requires.

07.11.2012
Matthias Frick
Ruby on Rails
6 Kommentare

Über den Autor

Matthias Frick
Matthias Frick, MSc.

Er ist ein langjähriger Ruby-on-Rails Entwickler und leitet das Unternehmen Frick-Web.

6 Kommentare zu "a short story about ruby modules and classes"

  1. April Meyer
    April Meyer 07.11.2012
    Very great article i love your site.
  2. Lukas Hofbaur
    Lukas Hofbaur 05.01.2013
    Thx for your explanation! Seems to be useful!
  3. Matthias Frick
    Matthias Frick 05.01.2013
    Nice to get such compliments. Thx very much :)!
  4. Laurie Sanderson
    Laurie Sanderson 16.01.2013
    Thx, it makes the modules quite clearer.
  5. Andrew Murpheys
    Andrew Murpheys 02.01.2014
    Interesting stuff guy.
  6. escuela infantil de torrejon de ardoz
    escuela infantil de torrejon de ardoz 01.02.2016
    Yo no estoy de acuerdo con lo aqui expuesto, pienso sinceramente que hay muchos aspectos que no han podido ser considerados en cuenta. Pero valoro mucho vuestra opinion, es un buen post. Saludos escuela infantil de torrejon de ardoz http://www.pequenaspromesas.com/escuela-infantil-torrejon-de-ardoz.html

Kommentar verfassen