Search code examples
rubymustache

Extract key names using Mustache Ruby API?


Does the Ruby Mustache API have a way to return the key names from a template?

Take, for example:

require 'mustache'
m = Mustache.new
m.template = "Hello {{first_name}} {{last_name}}"

I want to make an API call -- but I don't know what it is -- that returns the key names:

[:first_name, :last_name]

or something similar.


Solution

  • There isn't a way specifically to do that, but as a start you might consider the following:

    >> pp Mustache::Template.new('Hello {{first_name}} {{person.last_name}}').tokens
    [:multi,
     [:static, "Hello "],
     [:mustache, :etag, [:mustache, :fetch, ["first_name"]]],
     [:static, " "],
     [:mustache, :etag, [:mustache, :fetch, ["person", "last_name"]]]]
    

    It should be fairly easy to write a traversal that extracted the relevant keys.