Sha256: 6398e3682387f21c9303fec43b93b69855a0b45c8e53d6b8b43cd65f9ab93d78

Contents?: true

Size: 1.65 KB

Versions: 1

Compression:

Stored size: 1.65 KB

Contents

# =============================================================================
#
# MODULE      : lib/folder_template/template_string.rb
# PROJECT     : FolderTemplate
# DESCRIPTION :
#
# Copyright (c) 2016, Marc-Antoine Argenton.  All rights reserved.
# =============================================================================

module FolderTemplate
  class TemplateString
    attr_reader :content

    def initialize( template )
      case template
      when String
        @content = _parse( template )
      when Array
        @content = template.select do |fragment|
          !fragment.nil? && !fragment.empty?
        end
      when TemplateString
        @content = template.content
      end
    end

    def variables
      @variables ||= _extract_variables( @content )
    end

    def expand( **env )
      fragments = content.map do |fragment|
        case fragment
        when Symbol
          env[fragment] || (yield fragment if block_given?)|| fragment
        else
          fragment
        end
      end.select { |fragment| !fragment.nil? && !fragment.empty? }
      TemplateString.new( fragments )
    end

    def to_s
      @content.map do |fragment|
        ("{{#{fragment}}}" if Symbol === fragment) || fragment
      end.join
    end

  private
    VARIABLE_PATTERN = /{{(\w+)}}/

    def _parse( template )
      result = []
      tail = template
      loop do
        head, token, tail = tail.partition( VARIABLE_PATTERN )
        result << head if !head.empty?
        break if $1.nil?
        result << $1.to_sym
      end
      result
    end

    def _extract_variables( content )
      Set.new( content.select { |s| Symbol === s } )
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
folder_template-0.1.1 lib/folder_template/template_string.rb