Module: TypedAttributes::ClassMethods

Defined in:
lib/typed_attributes.rb

Instance Method Summary collapse

Instance Method Details

#field_accessor(attr, type_name, options = {}) ⇒ Object



28
29
30
31
# File 'lib/typed_attributes.rb', line 28

def field_accessor(attr, type_name, options = {})
  field_reader(attr, type_name, options)
  field_writer(attr, type_name, options)
end

#field_reader(attr, type_name, options = {}) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/typed_attributes.rb', line 7

def field_reader(attr, type_name, options = {})
  caster = type_caster_by_name(type_name).new(self, attr, options)
  caster.readers.each do |reader|
    define_method reader do
      unless instance_variable_defined?(caster.storage_var)
        instance_variable_set(caster.storage_var, options[:default]) 
      end
      instance_variable_get(caster.storage_var)
    end
  end
end

#field_writer(attr, type_name, options = {}) ⇒ Object



19
20
21
22
23
24
25
26
# File 'lib/typed_attributes.rb', line 19

def field_writer(attr, type_name, options = {})
  caster = type_caster_by_name(type_name).new(self, attr, options)
  caster.writers.each do |writer|
    define_method writer do |value|
      instance_variable_set(caster.storage_var, caster.parse(value))
    end
  end
end