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.



2184
2185
2186
2187
# File 'lib/warg.rb', line 2184

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

Instance Attribute Details

#contentObject (readonly)

Returns the value of attribute content.



2182
2183
2184
# File 'lib/warg.rb', line 2182

def content
  @content
end

Class Method Details

.find(relative_script_path, fail_if_missing: true) ⇒ Object



2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
# File 'lib/warg.rb', line 2134

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



2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
# File 'lib/warg.rb', line 2189

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