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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)