Sha256: a0596c0e4aabb53ac8e7c13488df9097af4bb6e5f805be04b2dfb8389ebd25e5

Contents?: true

Size: 1.38 KB

Versions: 1

Compression:

Stored size: 1.38 KB

Contents

autoload :Mustache, 'mustache'

module Omnitest
  class Psychic
    module Tokens
      class RegexpTokenHandler
        def initialize(template, token_pattern, token_replacement)
          @template = template
          @token_pattern = token_pattern
          @token_replacement = token_replacement
        end

        def tokens
          @template.scan(@token_pattern).flatten.uniq
        end

        def render(variables = {})
          @template.gsub(@token_pattern) do
            full_match = Regexp.last_match[0]
            key = Regexp.last_match[1]
            value = variables[key]
            value = @token_replacement.gsub('\\1', value.to_s) unless @token_replacement.nil?
            full_match.gsub(@token_pattern, value)
          end
        end
      end

      class MustacheTokenHandler
        def initialize(template)
          @template = Mustache::Template.new(template)
        end

        def tokens
          @template.tags
        end

        def render(variables = {})
          Mustache.render(@template, variables)
        end
      end

      def self.replace_tokens(template, variables, token_regexp = nil, token_replacement = nil)
        if token_regexp.nil?
          MustacheTokenHandler.new(template).render(variables)
        else
          RegexpTokenHandler.new(template, token_regexp, token_replacement).render(variables)
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
omnitest-psychic-0.0.9 lib/omnitest/psychic/tokens.rb