Class: Dhall::Coder

Inherits:
Object
  • Object
show all
Defined in:
lib/dhall/coder.rb

Defined Under Namespace

Modules: InitWith, ToRuby Classes: Verifier

Constant Summary collapse

JSON_LIKE =
[
	::Array, ::Hash,
	::TrueClass, ::FalseClass, ::NilClass,
	::Integer, ::Float, ::String
].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(default: nil, safe: JSON_LIKE) ⇒ Coder

Returns a new instance of Coder.



46
47
48
49
50
# File 'lib/dhall/coder.rb', line 46

def initialize(default: nil, safe: JSON_LIKE)
	@default = default
	@verifier = Verifier.new(*Array(safe))
	@verifier.verify(default, "default value")
end

Class Method Details

.dump(obj) ⇒ Object



42
43
44
# File 'lib/dhall/coder.rb', line 42

def self.dump(obj)
	new.dump(obj)
end

.load(source, transform_keys: :to_s, timeout: 10) ⇒ Object



38
39
40
# File 'lib/dhall/coder.rb', line 38

def self.load(source, transform_keys: :to_s, timeout: 10)
	new.load(source, transform_keys: transform_keys, timeout: timeout)
end

Instance Method Details

#decode(expr, op = "decode", klass: nil, transform_keys: :to_s) ⇒ Object



179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/dhall/coder.rb', line 179

def decode(expr, op="decode", klass: nil, transform_keys: :to_s)
	return revive(klass, expr, op, transform_keys: transform_keys) if klass
	@verifier.verify(
		Util.transform_keys(
			expr.to_ruby { |dexpr, dklass|
				decode(dexpr, op, klass: dklass, transform_keys: transform_keys)
			},
			&transform_keys
		),
		op
	)
end

#dump(obj) ⇒ Object



192
193
194
195
196
# File 'lib/dhall/coder.rb', line 192

def dump(obj)
	return if obj.nil?

	Dhall.dump(@verifier.verify(obj, "dump"))
end

#load(source, transform_keys: :to_s, timeout: 10) ⇒ Object



61
62
63
# File 'lib/dhall/coder.rb', line 61

def load(source, transform_keys: :to_s, timeout: 10)
	load_async(source, "load", transform_keys: transform_keys, timeout: timeout).sync
end

#load_async(source, op = "load_async", transform_keys: :to_s, timeout: 10) ⇒ Object



52
53
54
55
56
57
58
59
# File 'lib/dhall/coder.rb', line 52

def load_async(source, op="load_async", transform_keys: :to_s, timeout: 10)
	return Promise.resolve(@default) if source.nil?
	return Promise.resolve(source) unless source.is_a?(String)

	Dhall.load(source, timeout: timeout).then do |expr|
		decode(expr, op, transform_keys: transform_keys)
	end
end

#revive(klass, expr, op = "revive", transform_keys: :to_s) ⇒ Object



167
168
169
170
171
172
173
174
175
176
177
# File 'lib/dhall/coder.rb', line 167

def revive(klass, expr, op="revive", transform_keys: :to_s)
	@verifier.verify_class(klass, op)
	return klass.from_dhall(expr) if klass.respond_to?(:from_dhall)

	klass.allocate.tap do |o|
		o.init_with(Util.psych_coder_for(
			klass.name,
			decode(expr, op, transform_keys: transform_keys)
		))
	end
end