Class: Yop::Template

Inherits:
Object
  • Object
show all
Includes:
FileUtils
Defined in:
lib/yop/templates.rb

Overview

A Yop Template, which consists of a base directory and an hash of variables

Constant Summary collapse

DYNAMIC_PREFIX =

The prefix used for dynamic variables

Regexp.escape "!"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base_directory, vars = {}, config = {}) ⇒ Template

Create a new template from a base directory

Parameters:

  • base_directory (String)

    a path to an existing directory which will be used as a source when this template will be applied

  • vars (Hash) (defaults to: {})

    variables to use in this template. If a variable is found in the template but isn’t in the hash it’ll be retrieved from the template’s ui (default is Yop::TerminalUI).

  • config (Hash) (defaults to: {})

    additional configuration options



47
48
49
50
51
52
53
# File 'lib/yop/templates.rb', line 47

def initialize(base_directory, vars = {}, config = {})
  @base = base_directory
  @vars = vars
  @config = config

  compile_var_pattern!
end

Instance Attribute Details

#ui=(value) ⇒ Yop::UI (writeonly)

The UI used to get unknown variables

Parameters:

Returns:



35
36
37
# File 'lib/yop/templates.rb', line 35

def ui=(value)
  @ui = value
end

Instance Method Details

#[]=(name, value) ⇒ Any

Shortcut to add a template variable

Parameters:

  • name (Any)

    the variable’s name

  • value (Any)

    the variable’s value

Returns:

  • (Any)

    the provided value



94
95
96
# File 'lib/yop/templates.rb', line 94

def []=(name, value)
  @vars[name.to_s] = value
end

#apply(directory) ⇒ Object

Apply the template on a directory. It creates it if it doesn’t exist, then recursively copies itself in it

Parameters:

  • directory (String)

    the directory in which to copy

Returns:

  • nil



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/yop/templates.rb', line 59

def apply(directory)
  mkdir_p directory

  # get relative paths
  sources = []
  cd(@base) { sources = Dir["**/*", "**/.*"] }

  cd directory do
    sources.each do |path|
      next if skip? path

      source = "#{@base}/#{path}"
      path = replace_vars_in_path path

      if File.symlink? source
        copy_entry source, path
      elsif File.directory? source
        mkdir_p path
      elsif File.file? source
        File.open(path, "w") do |f|
          content = replace_vars source
          f.write(content)
        end
      else
        fail UnsupportedFileType, source
      end
      mirror_perms source, path
    end
  end
end