Module: Interfaces::TypedAccessors

Included in:
Class
Defined in:
lib/interfaces/typed_accessors.rb

Instance Method Summary collapse

Instance Method Details

#typed_attr_accessor(attrs) ⇒ Object

use like: typed_attr_accessor :field_name => InterfaceName



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/interfaces/typed_accessors.rb', line 5

def typed_attr_accessor(attrs)
  # attrs.each_pair |attr_name,interface|
  #   inst_variable_name = "@#{attr_name}"
  #   define_method method_name do
  #     instance_variable_get inst_variable_name
  #   end
  # end

  # use the standard reader
  attrs.keys.each do |attr|
    attr_reader attr
  end

  # also define writers
  typed_attr_writer attrs
end

#typed_attr_writer(attrs) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/interfaces/typed_accessors.rb', line 22

def typed_attr_writer(attrs)
  attrs.each_pair do |attr_name,interface|
    inst_variable_name = "@#{attr_name}"
    define_method "#{attr_name}=" do |new_value|
      instance_variable_set inst_variable_name, new_value ? new_value.as(interface) : nil
    end
  end
end