Module: JSI::BaseHash

Includes:
Hashlike
Defined in:
lib/jsi/base.rb

Overview

module extending a Base object when its schema instance is Hash-like (responds to #to_hash)

Constant Summary

Constants included from Hashlike

Hashlike::DESTRUCTIVE_METHODS, Hashlike::SAFE_KEY_ONLY_METHODS, Hashlike::SAFE_KEY_VALUE_METHODS, Hashlike::SAFE_METHODS

Instance Method Summary collapse

Methods included from Hashlike

#inspect, #pretty_print, #to_s

Instance Method Details

#[](property_name_) ⇒ JSI::Base, Object

Returns the instance's subscript value at the given key property_name_. if there is a subschema defined for that property on this JSI's schema, returns the instance's subscript as a JSI instiation of that subschema.

Returns:

  • (JSI::Base, Object)

    the instance's subscript value at the given key property_name_. if there is a subschema defined for that property on this JSI's schema, returns the instance's subscript as a JSI instiation of that subschema.



366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/jsi/base.rb', line 366

def [](property_name_)
  memoize(:[], property_name_) do |property_name|
    begin
      property_schema = schema.subschema_for_property(property_name)
      property_schema = property_schema && property_schema.match_to_instance(instance[property_name])

      if property_schema && instance[property_name].is_a?(JSON::Node)
        JSI.class_for_schema(property_schema).new(instance[property_name], origin: @origin)
      else
        instance[property_name]
      end
    end
  end
end

#[]=(property_name, value) ⇒ Object

assigns the given property name of the instance to the given value. if the value is a JSI, its instance is assigned.

Parameters:

  • property_name (Object)

    this should generally be a String, but JSI does not enforce any constraint on it.

  • value (Object)

    the value to be assigned to the given subscript property_name



387
388
389
# File 'lib/jsi/base.rb', line 387

def []=(property_name, value)
  subscript_assign(property_name, value)
end

#each {|Object, Object| ... } ⇒ self, Enumerator

yields each key and value of this JSI. each yielded key is the same as a key of the instance, and each yielded value is the result of selfkey. returns an Enumerator if no block is given.

Yields:

  • (Object, Object)

    each key and value of this JSI hash

Returns:

  • (self, Enumerator)


343
344
345
346
347
# File 'lib/jsi/base.rb', line 343

def each
  return to_enum(__method__) { instance.size } unless block_given?
  instance.each_key { |k| yield(k, self[k]) }
  self
end

#to_hashHash

Returns a hash in which each key is a key of the instance hash and each value is the result of selfkey.

Returns:

  • (Hash)

    a hash in which each key is a key of the instance hash and each value is the result of selfkey.



351
352
353
# File 'lib/jsi/base.rb', line 351

def to_hash
  inject({}) { |h, (k, v)| h[k] = v; h }
end