Class: General::GBaseTemplate

Inherits:
Object
  • Object
show all
Defined in:
lib/gtemplates/gbasetemplate.rb

Overview

Created: 7 - 30 - 2016

Direct Known Subclasses

GTemplate, GTimeFormat

Instance Method Summary collapse

Constructor Details

#initialize(string, partials) ⇒ GBaseTemplate

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



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# 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

Instance Method Details

#apply(data = {}) ⇒ Object

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



65
66
67
68
69
70
71
72
# 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) ⇒ Object

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



82
83
84
# File 'lib/gtemplates/gbasetemplate.rb', line 82

def apply_all array
	array.collect { |data| apply(data) }
end

#to_sObject

Returns a string representation of the template

Return: a string representation of the template



89
90
91
92
93
94
95
96
# 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