Class: Guider::Template

Inherits:
Object
  • Object
show all
Defined in:
lib/guider/template.rb

Overview

Reads a template from file. Allows replacing placeholders inside it.

Direct Known Subclasses

DefaultTemplate

Instance Method Summary collapse

Constructor Details

#initialize(path, defaults = {}) ⇒ Template

Takes path to the template and an optional defaults hash mapping placeholders to values. These are the default values for placeholders for which no value is given in the hash passed to #apply method.



9
10
11
12
# File 'lib/guider/template.rb', line 9

def initialize(path, defaults={})
  @template = IO.read(path)
  @defaults = defaults
end

Instance Method Details

#apply(hash) ⇒ Object

Sets the values for placeholders inside template. Returns the template text with placeholders replaced.



16
17
18
19
20
21
22
# File 'lib/guider/template.rb', line 16

def apply(hash)
  hash = @defaults.merge(hash)
  @template.gsub(/\{\w+\}/) do |placeholder|
    placeholder =~ /\{(.*)\}/
    hash[$1.to_sym]
  end
end