Read more

Subclassing module

Andreas Robecke
November 13, 2016Software engineer

Yesterday I stumbled across a talk in which the guy mentioned module sub-classing. I was curious what you can do with it and found his blog post with a cool example. It allows you to inject some state into the module you are including elsewhere. Check it out!

class AttributeAccessor < Module
  def initialize(name)
    @name = name
  end

  def included(model)
    super
    define_accessors
  end

  private

  def define_accessors
    ivar = "@#{@name}"
    define_writer(ivar)
    define_reader(ivar)
  end

  def define_writer(ivar)
    define_method("#{@name}=") do |value|
      instance_variable_set("#{ivar}", value)
    end
  end

  def define_reader(ivar)
    define_method(@name) do
      instance_variable_get("#{ivar}")
    end
  end
end

class Book
  include AttributeAccessor.new(:title)

  def title
    "#{super} + super works!"
  end
end

book = Book.new
book.title = "Module Subclassing Guide"
puts book.title
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

We also have a gem to help you with this: Modularity Show archive.org snapshot .
Modularity enhances Ruby's Module so it can be used with traits and partial classes. This allows very simple definition of meta-programming macros like the has_many that you know from Rails.
Modularity also lets you organize large models into multiple source files in a way that is less awkward than using modules.

Posted by Andreas Robecke to makandra dev (2016-11-13 15:15)