class General::GBaseTemplate

The base class for General template objects Implementing objects must define a :apply method Which applies the GTemplate to an object

Author: Anshul Kharbanda Created: 7 - 30 - 2016

Public Class Methods

new(string, partials) click to toggle source

Initializes the GBaseTemplate with the given string

Parameter: string - the string to initialize the GBaseTemplate with Parameter: partials - the partials used to parse the GBaseTemplate string

# File lib/gtemplates/gbasetemplate.rb, line 35
def initialize string, partials
        # Variables
        @partials = []
        @defaults = General::GDotHash.new

        # Partial breakdown algorithm
        m = nil
        loop do
                # Match the front of the string to a partial
                partial = partials.find { |partial| m = partial::REGEX.match(string) }

                # Raise error if no matching partial can be found
                raise GError.new("Unmatched character at #{(string.length <= 5 ? string : string[0..5] + "...").inspect}") if partial.nil?
                
                # Add the partial to the array
                @partials << partial.new(m, @defaults)

                # Trim the front of the string
                string = string[m.end(0)..-1]

                # End when string is empty
                return if string.length == 0
        end
end

Public Instance Methods

apply(data={}) click to toggle source

Applies the given data to the template and returns the generated string

Parameter: data - the data to be applied (as a hash. merges with defaults)

Return: string of the template with the given data applied

# File lib/gtemplates/gbasetemplate.rb, line 65
def apply data={}
        # Apply generalized data if can be generalized. Else apply regular data
        if data.respond_to? :generalized
                return apply(data.generalized)
        else
                return @partials.collect { |part| part.apply(data) }.join
        end
end
apply_all(array) click to toggle source

Applies each data structure in the array independently to the template and returns an array of the generated strings

Parameter: array - the array of data to be applied

(each data hash will be merged with defaults)

Return: array of strings generated from the template with the given

data applied
# File lib/gtemplates/gbasetemplate.rb, line 82
def apply_all array
        array.collect { |data| apply(data) }
end
to_s() click to toggle source

Returns a string representation of the template

Return: a string representation of the template

# File lib/gtemplates/gbasetemplate.rb, line 89
def to_s
        first = Hash.new(true); str = ""
        @partials.each do |part|
                str += part.string(first[part.name])
                first[part.name] &&= false
        end
        return str
end