Module: ROM::ClassMacros

Defined in:
lib/rom/support/class_macros.rb

Overview

Internal support module for class-level settings

Instance Method Summary collapse

Instance Method Details

#defines(*args) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Specify what macros a class will use

Examples:

class MyClass
  extend ROM::ClassMacros

  defines :one, :two

  one 1
  two 2
end

class OtherClass < MyClass
  two 'two'
end

MyClass.one # => 1
MyClass.two # => 2

OtherClass.one # => 1
OtherClass.two # => 'two'


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/rom/support/class_macros.rb', line 29

def defines(*args)
  mod = Module.new

  args.each do |name|
    mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1
      def #{name}(value = Undefined)
        if value == Undefined
          defined?(@#{name}) && @#{name}
        else
          @#{name} = value
        end
      end
    RUBY
  end

  delegates = args.map { |name| "klass.#{name}(#{name})" }.join("\n")

  mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1
    def inherited(klass)
      super
      #{delegates}
    end
  RUBY

  extend(mod)
end