Module: AttributedObject::Base::InstanceMethods

Included in:
Coerce::InstanceMethods, Strict::InstanceMethods
Defined in:
lib/attributed_object/base.rb

Instance Method Summary collapse

Instance Method Details

#==(other) ⇒ Object



94
95
96
# File 'lib/attributed_object/base.rb', line 94

def ==(other)
  self.class == other.class && self.attributes == other.attributes
end

#as_json(options = nil) ⇒ Object



98
99
100
101
102
# File 'lib/attributed_object/base.rb', line 98

def as_json(options=nil)
  attrs = self.attributes
  return attrs.as_json(options) if attrs.respond_to?(:as_json)
  {}.merge(attrs)
end

#attributesObject



54
55
56
57
58
# File 'lib/attributed_object/base.rb', line 54

def attributes
  Hash[self.class.attribute_defs.map { |name, _|
    [name, self.send(name)]
  }]
end

#initialize(args = {}) ⇒ Object



50
51
52
# File 'lib/attributed_object/base.rb', line 50

def initialize(args={})
  initialize_attributes(args)
end

#initialize_attributes(args) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/attributed_object/base.rb', line 60

def initialize_attributes(args)
  symbolized_args = AttributedObjectHelpers::HashUtil.symbolize_keys(args)
  if !self.class.attributed_object_options.fetch(:ignore_extra_keys)
    symbolized_args.keys.each do |key|
      if !self.class.attribute_defs.keys.include?(key)
        raise UnknownAttributeError.new(self.class, key, args)
      end
    end
  else
    symbolized_args = AttributedObjectHelpers::HashUtil.slice(symbolized_args, self.class.attribute_defs.keys)
  end

  self.class.attribute_defs.each { |name, opts|
    if !symbolized_args.has_key?(name)
      default = opts[:default]
      default = default.call if default.respond_to?(:call)
      symbolized_args[name] = default unless default == Unset
    end

    if !symbolized_args.has_key?(name)
      raise MissingAttributeError.new(self.class, name, args)
    end

    if opts[:disallow] != Unset && symbolized_args[name] == opts[:disallow]
      raise DisallowedValueError.new(self.class, name, args)
    end

    if opts[:type_info] != Unset && symbolized_args[name] != nil
      symbolized_args[name] = _attributed_object_on_init_attribute(opts[:type_info], symbolized_args[name], name: name, args: args)
    end
    self.send("#{name}=", symbolized_args[name])
  }
end