Posted over 8 years ago. Visible to the public.

Defining and using sub-classes with modularity

Given this class:

class Foo class Bar end end

If you want to clean up this code with the modularity gem, 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.

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Arne Hartherz
Last edit:
over 4 years ago
by Besprechungs-PC
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more