Module: Attributary::DSL::Accessors

Included in:
ClassMethods
Defined in:
lib/attributary/dsl/accessors.rb

Instance Method Summary collapse

Instance Method Details

#_attributary_default_for_method(type, value) ⇒ Object



42
43
44
45
# File 'lib/attributary/dsl/accessors.rb', line 42

def _attributary_default_for_method(type, value)
  return nil if value.nil?
  _attributary_cast_to(type, value)
end

#_attributary_reader(name, type, options) ⇒ Object



31
32
33
34
35
36
37
38
39
40
# File 'lib/attributary/dsl/accessors.rb', line 31

def _attributary_reader(name, type, options)
  define_method(name) do
    instance_variable_get(:"@#{name}") || self.class._attributary_default_for_method(type, options[:default])
  end
  if type == :boolean
    define_method("#{name}?") do
      send(name.to_s)
    end
  end
end

#_attributary_writer(name, type, options) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/attributary/dsl/accessors.rb', line 12

def _attributary_writer(name, type, options)
  define_method("#{name}=") do |value|
    value = self.class._attributary_cast_to(type, value) unless self.class._attributary_config.strict_mode?
    write = true
    write = self.class._attributary_check_collection(name, value, options[:collection]) if options[:collection].is_a?(Array)
    write = self.class._attributary_validate_attribute(name, value, options[:validate]) if options[:validate].is_a?(Proc)
    if options[:validate].is_a?(Symbol)
      unless send(options[:validate])
        self.class._attributary_handle_error(name, value, :validation)
        write = false
      end
    end
    if write
      instance_variable_set(:"@#{name}", value)
      self.class._attributary_errors.delete(name)
    end
  end
end