module STAC::HashLike

Enables included class to behave like Hash.

Attributes

extra[R]

Extra fields that do not belong to the STAC core specification.

Public Instance Methods

==(other) click to toggle source

Returns ‘true` if all of the followings are true:

  • the given object is an instance of tha same class

  • ‘self.to_hash == other.to_hash`

Otherwise, returns ‘false`.

# File lib/stac/hash_like.rb, line 60
def ==(other)
  other.instance_of?(self.class) && to_hash == other.to_hash
end
[](key) click to toggle source

When there is an attribute with the given name, returns the attribute value. Otherwise, calls ‘extra [key]`.

# File lib/stac/hash_like.rb, line 13
def [](key)
  if respond_to?(key) && method(key).arity.zero?
    public_send(key)
  else
    extra[key.to_s]
  end
end
[]=(key, value) click to toggle source

When there is an attribute writer with the given name, assigns the value to the attribute. Otherwise, adds the given key-value pair to ‘extra` hash.

# File lib/stac/hash_like.rb, line 23
def []=(key, value)
  method = "#{key}="
  if respond_to?(method)
    public_send(method, value)
  else
    extra[key.to_s] = value
  end
end
deep_dup() click to toggle source

Returns a copy of self by serializes self to a JSON and desirializes it by ‘.from_hash`.

# File lib/stac/hash_like.rb, line 65
def deep_dup
  unless self.class.respond_to?(:from_hash)
    raise NotImplementedError, "#{self.class} must implement `.from_hash(hash)` to use `HashLike#deep_dup`"
  end

  hash = JSON.parse(to_json)
  self.class.from_hash(hash)
end
to_h() click to toggle source

Serializes self to a Hash.

# File lib/stac/hash_like.rb, line 46
def to_h
  extra
end
to_json(...) click to toggle source

Serializes self to a JSON string.

# File lib/stac/hash_like.rb, line 51
def to_json(...)
  to_h.to_json(...)
end
update(**options) click to toggle source

Sets the attributes (like ActiveModel::AttributeAssignment#assign_attributes) or merges the args into ‘extra` hash (like Hash#update).

# File lib/stac/hash_like.rb, line 34
def update(**options)
  options.each do |key, value|
    self[key] = value
  end
  self
end