Module: Interfacer

Defined in:
lib/interfacer.rb

Instance Method Summary collapse

Instance Method Details

#attribute(attr_name, *required_methods, &block) ⇒ Object


41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/interfacer.rb', line 41

def attribute(attr_name, *required_methods, &block)
  interface_specs_for_attrs[attr_name] = InterfaceSpec.new(required_methods)

  define_method(attr_name) do
    value = instance_variable_get(:"@#{attr_name}")
    return value if value
    instance_variable_set(:"@#{attr_name}", block.call) if block
  end

  define_method(:"#{attr_name}=") do |value|
    spec = self.class.interface_specs_for_attrs[attr_name]

    unless spec.fullfills_interface?(value)
      raise InterfaceRequirementsNotMetError.new(attr_name, spec.missing_methods(value))
    end

    instance_variable_set(:"@#{attr_name}", value)
  end
end

#interface_specs_for_attrsObject


37
38
39
# File 'lib/interfacer.rb', line 37

def interface_specs_for_attrs
  @interface_specs_for_attrs ||= Hash.new
end