Sha256: 8d4eae5b91fbcc55c8614b59dcd5e92e3ff1196e4c727f17980cb207debc7f0d

Contents?: true

Size: 862 Bytes

Versions: 2

Compression:

Stored size: 862 Bytes

Contents

module ROCrate
  ##
  # A wrapper class for Hash that adds methods to dereference Entities within an RO Crate.
  class JSONLDHash < ::Hash
    def initialize(graph, content = {})
      @graph = graph
      super()
      update(stringified(content))
    end

    def [](key)
      jsonld_wrap(super)
    end

    def dereference
      @graph.dereference(self['@id']) if self['@id']
    end

    def has_type?(type)
      t = self['@type']
      t.is_a?(Array) ? t.include?(type) : t == type
    end

    private

    def jsonld_wrap(val)
      if val.is_a?(Array)
        val.map { |v| jsonld_wrap(v) }
      elsif val.instance_of?(::Hash)
        self.class.new(@graph, val)
      else
        val
      end
    end

    # A slow and stupid way of making sure all hash keys are strings.
    def stringified(hash)
      JSON.parse(hash.to_json)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
ro-crate-0.4.1 lib/ro_crate/json_ld_hash.rb
ro-crate-0.4.0 lib/ro_crate/json_ld_hash.rb