Read more

Defining and using sub-classes with modularity

Arne Hartherz
November 05, 2010Software engineer at makandra GmbH

Given this class:

class Foo
  class Bar
  end
end
Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

If you want to clean up this code with the modularity gem Show archive.org snapshot , you might try something like this:

class Foo
  does 'bar'
end

module BarTrait
  as_trait do
    class Bar
    end
  end
end

Note that this changes Bar's full class name from Foo::Bar to BarTrait::Bar. If you have methods inside Foo (or other classes), you would have to change all references accordingly, which is quite unpleasant.

You can solve it like that:

module BarTrait
  as_trait do
    class self::Bar
    end
  end
end

This gives you Foo::Bar back (or if the Baz class also uses the trait, Baz::Bar).

Class methods inside Foo can refer to Bar like before -- if you put such class methods into traits, they will have to use self::Bar, too.

Posted by Arne Hartherz to makandra dev (2010-11-05 12:04)