module AttributedObject::Base::InstanceMethods

Public Class Methods

new(args={}) click to toggle source
# File lib/attributed_object/base.rb, line 61
def initialize(args={})
  initialize_attributes(args)
end

Public Instance Methods

==(other) click to toggle source
# File lib/attributed_object/base.rb, line 110
def ==(other)
  self.class == other.class && self.attributes == other.attributes
end
as_json(options=nil) click to toggle source
# 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
attributes() click to toggle source
# File lib/attributed_object/base.rb, line 65
def attributes
  Hash[self.class.attribute_defs.map { |name, _|
    [name, self.send(name)]
  }]
end
initialize_attributes(args) click to toggle source
# 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