Class: Attrio::Builders::WriterBuilder

Inherits:
AccessorBuilder show all
Defined in:
lib/attrio/builders/writer_builder.rb

Class Method Summary collapse

Methods inherited from AccessorBuilder

define, define_aliases

Class Method Details

.accessorObject



8
9
10
# File 'lib/attrio/builders/writer_builder.rb', line 8

def self.accessor
  :writer
end

.define_accessor(klass, type, options) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/attrio/builders/writer_builder.rb', line 12

def self.define_accessor(klass, type, options)
  unless klass.method_defined?(options[:method_name])
    if type.present?
      self.define_typecasting_method(klass, type, options)
    else
      klass.send :attr_writer, options[:method_name].chop
    end

    klass.send options[:method_visibility], options[:method_name]
  end
end

.define_typecasting_method(klass, type, options) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/attrio/builders/writer_builder.rb', line 24

def self.define_typecasting_method(klass, type, options)
  klass.send :define_method, options[:method_name] do |value|
    if !value.nil?
      value = if type.respond_to?(:typecast) && type.respond_to?(:typecasted?)
        type.typecasted?(value, options) ? value : type.typecast(*[value, options])
      else
        type == Hash && value.is_a?(Hash) ? value : type.new(value)
      end
    end

    self.instance_variable_set(options[:instance_variable_name], value)
  end
end