Posted over 11 years ago. Visible to the public.

Defining and using sub-classes with modularity

Given this class:

Copy
class Foo class Bar end end

If you want to clean up this code with the modularity gem Archive , you might try something like this:

Copy
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:

Copy
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:

Avatar
Arne Hartherz
Last edit:
about 7 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 short-lived cookies to improve usability.
Accept or learn more