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



110
111
112
# File 'lib/attributed_object/base.rb', line 110

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

#as_json(options = nil) ⇒ Object



114
115
116
117
118
# File 'lib/attributed_object/base.rb', line 114

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

#attributesObject



65
66
67
68
69
# File 'lib/attributed_object/base.rb', line 65

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

#initialize(args = {}) ⇒ Object



61
62
63
# File 'lib/attributed_object/base.rb', line 61

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

#initialize_attributes(args) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/attributed_object/base.rb', line 71

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

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

    self.send("#{name}=", symbolized_args[name])
  }
end