Class: Warg::Script::Template

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

Defined Under Namespace

Classes: Missing

Constant Summary collapse

INTERPOLATION_REGEXP =
/%{([\w:]+)}/
MISSING =
Missing.new

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path) ⇒ Template

Returns a new instance of Template.


2098
2099
2100
2101
# File 'lib/warg.rb', line 2098

def initialize(file_path)
  @path = file_path
  @content = @path.read
end

Instance Attribute Details

#contentObject (readonly)

Returns the value of attribute content


2096
2097
2098
# File 'lib/warg.rb', line 2096

def content
  @content
end

Class Method Details

.find(relative_script_path, fail_if_missing: true) ⇒ Object


2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
# File 'lib/warg.rb', line 2048

def self.find(relative_script_path, fail_if_missing: true)
  extension = File.extname(relative_script_path)
  relative_paths = [relative_script_path]

  if extension.empty?
    relative_paths << "#{relative_script_path}.sh"
  else
    relative_paths << relative_script_path.chomp(extension)
  end

  paths_checked = []

  script_path = Warg.search_paths.inject(nil) do |path, directory|
    relative_paths.each do |relative_path|
      target_path = directory.join("scripts", relative_path)
      paths_checked << target_path

      if target_path.exist?
        path = target_path
      end
    end

    if path
      break path
    end
  end

  if script_path
    new(script_path)
  elsif fail_if_missing
    raise <<~ERROR
      ScriptNotFoundError: Could not find `#{relative_script_path}'
        Looked in:
          #{paths_checked.join("\n")}
    ERROR
  else
    MISSING
  end
end

Instance Method Details

#compile(interpolations) ⇒ Object


2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
# File 'lib/warg.rb', line 2103

def compile(interpolations)
  @content.gsub(INTERPOLATION_REGEXP) do |match|
    if interpolations.key?($1)
      interpolations[$1]
    else
      $stderr.puts "[WARN] `#{$1}' is not defined in interpolations or context variables"
      $stderr.puts "[WARN]   leaving interpolation `#{match}' as is"
      match
    end
  end
end