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
-
.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.
-
.modified_copy(object) {|Object| ... } ⇒ object.class
yields the content of the given param
object
.
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.
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/jsi/typelike_modules.rb', line 39 def self.as_json(object, *opt) if object.is_a?(JSI::PathedNode) as_json(object.jsi_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 #jsi_modified_copy
method of their own (JSI::Base, JSI::MetaschemaNode) 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).
16 17 18 19 20 21 22 |
# File 'lib/jsi/typelike_modules.rb', line 16 def self.modified_copy(object, &block) if object.respond_to?(:jsi_modified_copy) object.jsi_modified_copy(&block) else return yield(object) end end |