Sha256: 536ee47c6feb381a6fa856ae795151666d90785898ecd54ab447fb31eecd9680

Contents?: true

Size: 842 Bytes

Versions: 6

Compression:

Stored size: 842 Bytes

Contents

require 'mustache'
module HSQL
  # Given some SQL that may contain Mustache tags (e.g. {{{ variable }}} ),
  # accept a hash of data that interpolates each tag.
  # Throws an error if one of the tag names can't be found in the data.
  class Template
    attr_reader :input

    def initialize(input)
      @input = input
    end

    def variable_names
      extract_variable_names(ast).uniq
    end

    def render(hash)
      Mustache.render(input, hash)
    end

    private

    # See Mustache::Generator#compile! for reference code
    def extract_variable_names(tree)
      return unless tree.is_a?(Array)
      if tree[1] == :fetch
        tree.last.first
      else
        tree.map { |token| extract_variable_names(token) }.flatten.compact
      end
    end

    def ast
      ::Mustache::Parser.new.compile(input)
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
hsql-0.3.5 lib/hsql/template.rb
hsql-0.3.4 lib/hsql/template.rb
hsql-0.3.3 lib/hsql/template.rb
hsql-0.3.2 lib/hsql/template.rb
hsql-0.3.1 lib/hsql/template.rb
hsql-0.3.0 lib/hsql/template.rb