class Geny::Actions::Templates

Utilities for rendering and copying templates. @see rubydoc.info/github/piotrmurach/tty-file/master/TTY/File TTY::File

Public Class Methods

new(root:, view:) click to toggle source

Creates a new instance @param root [String] the root path where templates live @param view [View] a view that exposes locals and helpers

# File lib/geny/actions/templates.rb, line 12
def initialize(root:, view:)
  @root = root
  @view = view
end

Public Instance Methods

copy(source, *args, **opts) click to toggle source

Copy a template file. The file will be evaluated with ERB. All command-line options and helper methods are available in the template.

@example

templates.copy("hello.erb", "hello.txt")
templates.copy("hello.erb", "hello.txt", locals: {name: "world"})
# File lib/geny/actions/templates.rb, line 24
def copy(source, *args, **opts)
  source = expand_path(source)
  context, opts = build_context(**opts)
  TTY::File.copy_file(source, *args, context: context, **opts)
end
copy_dir(source, *args, **opts) click to toggle source

Copy a template directory. All files will be evaluated with ERB. All command-line options and helper methods are available in the template.

@example

templates.copy_dir("boilerplate", output)
templates.copy_dir("boilerplate", output, locals: {name: "world"})
# File lib/geny/actions/templates.rb, line 37
def copy_dir(source, *args, **opts)
  source = expand_path(source)
  context, opts = build_context(**opts)
  TTY::File.copy_dir(source, *args, context: context, **opts)
end
render(path, **opts) click to toggle source

Render an ERB template. All command-line options and helper methods are available in the template.

@example

templates.render("hello.erb")
templates.render("hello.erb", locals: {name: "world"})
# File lib/geny/actions/templates.rb, line 49
def render(path, **opts)
  path = expand_path(path)
  input = File.binread(path)
  context, _opts = build_context(**opts)
  erb = ERB.new(input, nil, "-", "@output_buffer")
  erb.result(context.instance_eval("binding"))
end

Private Instance Methods

build_context(locals: {}, **opts) click to toggle source
# File lib/geny/actions/templates.rb, line 59
def build_context(locals: {}, **opts)
  [@view.merge(locals), opts]
end
expand_path(path) click to toggle source
# File lib/geny/actions/templates.rb, line 63
def expand_path(path)
  File.expand_path(path, @root)
end