Module: JSI::Typelike

Defined in:
lib/jsi/typelike_modules.rb

Overview

a module relating to objects that act like Hash or Array instances

Class Method Summary collapse

Class Method Details

.as_json(object, *opt) ⇒ Array, ...

recursive method to express the given argument object in json-compatible types of Hash, Array, and basic types of String/boolean/numeric/nil. this will raise TypeError if an object is given that is not a type that seems to be expressable as json.

similar effect could be achieved by requiring 'json/add/core' and using

as_json, but I don't much care for how it represents classes that are

not naturally expressable in JSON, and prefer not to load its monkey-patching.

Parameters:

  • object (Object)

    the object to be converted to jsonifiability

Returns:

  • (Array, Hash, String, Boolean, NilClass, Numeric)

    jsonifiable expression of param object

Raises:

  • (TypeError)

    when the object (or an object nested with a hash or array of object) cannot be expressed as json



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/jsi/typelike_modules.rb', line 40

def self.as_json(object, *opt)
  if object.is_a?(JSI::PathedNode)
    as_json(object.node_content, *opt)
  elsif object.respond_to?(:to_hash)
    (object.respond_to?(:map) ? object : object.to_hash).map do |k, v|
      unless k.is_a?(Symbol) || k.respond_to?(:to_str)
        raise(TypeError, "json object (hash) cannot be keyed with: #{k.pretty_inspect.chomp}")
      end
      {k.to_s => as_json(v, *opt)}
    end.inject({}, &:update)
  elsif object.respond_to?(:to_ary)
    (object.respond_to?(:map) ? object : object.to_ary).map { |e| as_json(e, *opt) }
  elsif [String, TrueClass, FalseClass, NilClass, Numeric].any? { |c| object.is_a?(c) }
    object
  elsif object.is_a?(Symbol)
    object.to_s
  elsif object.is_a?(Set)
    as_json(object.to_a, *opt)
  elsif object.respond_to?(:as_json)
    as_json(object.as_json(*opt), *opt)
  else
    raise(TypeError, "cannot express object as json: #{object.pretty_inspect.chomp}")
  end
end

.modified_copy(object) {|Object| ... } ⇒ object.class

yields the content of the given param object. for objects which have a

modified_copy method of their own (JSI::Base, JSI::JSON::Node) that

method is invoked with the given block. otherwise the given object itself is yielded.

the given block must result in a modified copy of its block parameter (not destructively modifying the yielded content).

Yields:

  • (Object)

    the content of the given object. the block should result in a (nondestructively) modified copy of this.

Returns:

  • (object.class)

    modified copy of the given object



17
18
19
20
21
22
23
# File 'lib/jsi/typelike_modules.rb', line 17

def self.modified_copy(object, &block)
  if object.respond_to?(:modified_copy)
    object.modified_copy(&block)
  else
    return yield(object)
  end
end