Module: Babl::Operators::Object::DSL

Included in:
Template
Defined in:
lib/babl/operators/object.rb

Instance Method Summary collapse

Instance Method Details

#object(*args) ⇒ Object

Create a JSON object node with static structure



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/babl/operators/object.rb', line 11

def object(*args)
    kwargs = ::Hash === args.last ? args.pop : Utils::Hash::EMPTY

    (args.map(&:to_sym) + kwargs.keys.map(&:to_sym)).group_by(&:itself).each_value do |keys|
        raise Errors::InvalidTemplate, "Duplicate key in object(): #{keys.first}" if keys.size > 1
    end

    templates = args
        .map { |name| [name.to_sym, unscoped.nav(name)] }.to_h
        .merge(kwargs)
        .map { |k, v| [k, unscoped.call(v)] }

    construct_terminal { |ctx|
        Nodes::Object.new(templates.map { |key, template|
            [
                key.to_sym,
                template.builder.precompile(
                    Nodes::TerminalValue.instance,
                    ctx.merge(key: key, continue: nil)
                )
            ]
        }.to_h)
    }
end