Posted almost 5 years ago. Visible to the public.

Advanced Ruby: More metaprogramming with Modularity and ActiveSupport::Concern [2d]

Learn about method lookup

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

  • include
  • extend
  • singleton class
  • prepend

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?

Understand this article: Rails 5, Module#prepend, and the End of Alias_method_chain

Learn about metaprogramming libraries

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

Finding method definitions

Because we have metaprogramming, it might not be apparent where a method is defined.

Learn about Method#source_location

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 } login.remember_me = false login.remember_me # => false

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:
2 months ago
by Henning Koch
Posted by Tobias Kraze to makandra Curriculum
This website uses cookies to improve usability and analyze traffic.
Accept or learn more