Posted almost 3 years ago. Visible to the public.

Advanced Ruby: More metaprogramming with Modularity and ActiveSupport::Concern

Learn about method lookup

Understand all the terms in How Ruby method lookup works, in particular:

  • include
  • extend
  • singleton class

Do you understand why object.extend(SomeModule) is the same as object.singleton_class.include(SomeModule)?

How does include and extend work together with inheritance?

Learn about metaprogramming libraries

  • Find out how ActiveSupport::Concern works.
  • Understand the documentation for our Modularity 2 gem

Exercise: Virtual attributes with plain Ruby

Look at the following "mini Active Record" interface:

class Login include Attributes attribute :email attribute :password attribute :remember_me, default: true end login = = "" login.password = "mypassword" # => "" login.password # => "mypassword" login.remember_me # => true login.attributes # => { email: "", password: "mypassword", remember_me: true }

Implement the Attributes module in plain ruby, so it supports the API above.

Exercise: Virtual attributes with ActiveSupport::Concern

Add a second implementation AttributesConcern that uses ActiveSupport::Concern. Don't share code between your implementations.

It should work identical to the first implementation.

Exercise: Virtual attributes with Modularity

Add a third implementation DoesAttributes that uses Modularity.

For modularity we often use an alternative interface:

class Login include DoesAttribute[:email] include DoesAttribute[:password] include DoesAttribute[:remember_me, default: true] end

Implement this new interface.

Now compare your implementations. Which one do you like best?
Does modularity offer features the other approaches don't?

Owner of this card:

Tobias Kraze
Last edit:
almost 3 years ago
by Tobias Kraze
Posted by Tobias Kraze to makandra Curriculum
This website uses cookies to improve usability and analyze traffic.
Accept or learn more