Class: BoPeep::Script::Template

Inherits:
Object
  • Object
show all
Defined in:
lib/bopeep.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.



2255
2256
2257
2258
# File 'lib/bopeep.rb', line 2255

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

Instance Attribute Details

#contentObject (readonly)

Returns the value of attribute content.



2253
2254
2255
# File 'lib/bopeep.rb', line 2253

def content
  @content
end

Class Method Details

.find(relative_script_path, fail_if_missing: true) ⇒ Object



2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
# File 'lib/bopeep.rb', line 2205

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 = BoPeep.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



2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
# File 'lib/bopeep.rb', line 2260

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