class Splash::Templates::Template

KISS template Engine

Attributes

content[R]

getter of the flat content of the template

list_token[R]

getter of the list of token

template_file[R]

getter of the template file

Public Class Methods

new(_options) click to toggle source

constructor : generate the pseudo accessor for template Class from token list

# File lib/splash/templates.rb, line 20
def initialize(_options)


  @template_file = _options[:template_file]
  raise NoTemplateFile::new('No template file found') unless File::exist?(@template_file)
  begin
    @content = IO::readlines(@template_file).join.chomp
  rescue
    raise NoTemplateFile::new('No template file found')
  end
  token_from_template = @content.scan(/%%(\w+)%%/).flatten.uniq.map{ |item| item.downcase.to_sym}
  begin
    @list_token = _options[:list_token]
    @hash_token = Hash::new; @list_token.each{|_item| @hash_token[_item.to_s] = String::new('')}
  rescue
    raise InvalidTokenList::new("Token list malformation")
  end
  raise InvalidTokenList::new("Token list doesn't match the template") unless token_from_template.sort == @list_token.sort
  @list_token.each{|_token| eval("def #{_token}=(_value); raise ArgumentError::new('Not a String') unless _value.class == String; @hash_token['#{_token}'] = _value ;end")}
  @list_token.each{|_token| eval("def #{_token}; @hash_token['#{_token}'] ;end")}
end

Public Instance Methods

map(_hash) click to toggle source

map a hash against templates token_list @param [Hash] _hash a hash data to map

# File lib/splash/templates.rb, line 53
def map(_hash)
  _data = {}
  _hash.each { |item,val|
    raise ArgumentError::new("#{item} : Not a String") unless val.class == String
    _data[item.to_s.downcase] = val
  }
  raise InvalidTokenList::new("Token list malformation") unless _data.keys.sort == @list_token.map{|_token| _token.to_s }.sort
  @hash_token = _data
end
method_missing(_name,*_args) click to toggle source

collector for pseudo accessor to prevent bad mapping @raise [NotAToken] if caling an accessor not mapped in token list

# File lib/splash/templates.rb, line 65
def method_missing(_name,*_args)
  raise NotAToken
end
output() click to toggle source

the templater;proceed to templating @return [String] the template output

# File lib/splash/templates.rb, line 71
def output
  _my_res = String::new('')
  _my_res = @content
  @list_token.each{|_token|
    _my_res.gsub!(/%%#{_token.to_s.upcase}%%/,@hash_token[_token.to_s])
  }
  return _my_res
end
token(_token,_value) click to toggle source

generic accessor @param [Symbol] _token in the token list @param [String] _value a text value @raise [ArgumentError] if _valu is not a String

# File lib/splash/templates.rb, line 46
def token(_token,_value)
  raise ArgumentError::new('Not a String') unless _value.class == String
  @hash_token[_token.to_s] = _value
end