Lucas
Lucas

Reputation: 11

Allow lambdas with mustache on command line?

If I try to use ruby lambdas in my YAML frontmatter with command line mustache, it is treated as if it was straight text.

E.g. test.yaml:

name: Willy  
wrapped: proc { |text| "<b>#{text}</b>" }

template.mustache:

{{#wrapped}}
{{name}} is awesome.
{{/wrapped}}

Result on the command line:

$ mustache test.yaml template.mustache  
Willy is awesome.

On the other hand, in IRB:

irb(main):032:0> Mustache.render("{{#wrapped}}{{name}} is awesome.  
{{/wrapped}}", name: "Willy", wrapped: proc {|text| "<b>#{text}</b>"  
})

=> "<b>Willy is awesome.</b>"

Can I get the same result from the command line as when I use mustache from IRB?

Upvotes: 0

Views: 163

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Can I get the same result from the command line as when I use mustache from IRB?

No, you cannot.

The reason you get different results is that in IRB you pass a ruby hash object, having two keys. The key :wrapped is an instance of proc.

In YAML, OTOH, you have both values as strings. YAML has a very limited support of storing objects and I am not aware of any extension allowing the serialization of procs. The naïve attempt does not work:

{wrapped: proc { |text| "<b>#{text}</b>" }}.to_yaml
#⇒ "---\n:wrapped: !ruby/object:Proc {}\n"

Obviously, when loaded back, this will become a NOOP. You might hack this behaviour with something like:

YAML.load_file('/path/to/your/file.yaml').
  map { |k, v| [k, v.start_with?('proc') ? eval(v) : v] }.
  to_h[:wrapped].('Hi!')
#⇒ "<b>Hi!</b>"

But I would strongly suggest not to do that.

Upvotes: 1

Related Questions