Class: FileTemplater::Template

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

Instance Method Summary collapse

Constructor Details

#initialize(template, arguments, options = {}) ⇒ Template

options can include: bind: which binding rather than the default to use nomodify: if the template ERB will be loaded or not



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/file_templater/template.rb', line 6

def initialize(template, arguments, options = {})
  @nomodify = options[:nomodify]

  @template = File.join(HUBS[:template], template)
  binding_string = options[:bind] || template + ".rb"
  binding_file = File.join(HUBS[:binding], binding_string)
  using_binding = File.exist?(binding_file)

  if using_binding
    # Load the binding.
              FileActions.require_binding(binding_string)

    # Get the binding class name from the binding file,
    # and create an instance of it.
    binding_class = Object.const_get("Bindings::" + FileActions.get_class_name(binding_file))
    @bind = binding_class.new(*arguments)
  end
end

Instance Method Details

#load(folder = @template) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/file_templater/template.rb', line 25

def load(folder = @template)
  FileUtils.mkdir(File.basename(folder)) unless folder == @template

  FileActions.unique_directory_list(folder).each do |f|
    # We need the whole path to f, but we will keep the short name.
    short_name = f
    f = File.join(folder, f)

    if File.directory?(f)
      self.load f
    else
      if !@nomodify && f.end_with?(".erb")
        output_file = File.open(File.join(Dir.pwd, transform_file_name(short_name)), "w")

        input_file = File.open(f, "r")
        output_file.print(ERB.new(input_file.read, nil, "<>").result(@bind && @bind.get_binding))
        input_file.close

        output_file.close
      else
        FileUtils.copy_entry(f, File.join(Dir.pwd, transform_file_name(short_name)))
      end
    end
  end
end

#transform_file_name(file) ⇒ Object

Expands the variable-in-file-name notation. file is expected to be a short name



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/file_templater/template.rb', line 53

def transform_file_name(file)
  if @bind
    variables = file.scan(/{{([^}]*)}}/).flatten

    variables.each do |v|
      file.sub!("{{#{v}}}", @bind.get_binding.eval(v))
    end
  end

  !@nomodify && file.end_with?(".erb") ? File.basename(file, ".*") : file
end