Method: Thor::Actions#template

Defined in:
lib/thor/actions/file_manipulation.rb

#template(source, *args, &block) ⇒ Object

Gets an ERB template at the relative source, executes it and makes a copy at the relative destination. If the destination is not given it's assumed to be equal to the source removing .tt from the filename.

Parameters

source<String>

the relative path to the source root.

destination<String>

the relative path to the destination root.

config<Hash>

give :verbose => false to not log the status.

Examples

template "README", "doc/README"

template "doc/README"

115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/thor/actions/file_manipulation.rb', line 115

def template(source, *args, &block)
  config = args.last.is_a?(Hash) ? args.pop : {}
  destination = args.first || source.sub(/#{TEMPLATE_EXTNAME}$/, "")

  source  = File.expand_path(find_in_source_paths(source.to_s))
  context = config.delete(:context) || instance_eval("binding")

  create_file destination, nil, config do
    match = ERB.version.match(/(\d+\.\d+\.\d+)/)
    capturable_erb = if match && match[1] >= "2.2.0" # Ruby 2.6+
      CapturableERB.new(::File.binread(source), :trim_mode => "-", :eoutvar => "@output_buffer")
    else
      CapturableERB.new(::File.binread(source), nil, "-", "@output_buffer")
    end
    content = capturable_erb.tap do |erb|
      erb.filename = source
    end.result(context)
    content = yield(content) if block
    content
  end
end