class JsFromRoutes::Template

Internal: Represents a compiled template that can write itself to a file.

Public Class Methods

new(template_path) click to toggle source
# File lib/js_from_routes/generator.rb, line 89
def initialize(template_path)
  # NOTE: The compiled ERB template, used to generate JS code.
  @compiled_template = Erubi::Engine.new(File.read(template_path), filename: template_path).src
end

Public Instance Methods

write_if_changed(object) click to toggle source

Public: Checks if the cache is fresh, or renders the template with the specified variables, and writes the updated result to a file.

# File lib/js_from_routes/generator.rb, line 96
def write_if_changed(object)
  write_file_if_changed(object.filename, object.cache_key) { render_template(object) }
end

Private Instance Methods

render_template(object) click to toggle source

Internal: Returns a String with the generated JS code.

# File lib/js_from_routes/generator.rb, line 103
def render_template(object)
  object.instance_eval(@compiled_template)
end
stale?(file, cache_key_comment) click to toggle source

Internal: Returns true if the cache key has changed since the last codegen.

# File lib/js_from_routes/generator.rb, line 108
def stale?(file, cache_key_comment)
  ENV["JS_FROM_ROUTES_FORCE"] || file.gets != cache_key_comment
end
write_file_if_changed(name, cache_key) { || ... } click to toggle source

Internal: Writes if the file does not exist or the cache key has changed. The cache strategy consists of a comment on the first line of the file.

Yields to receive the rendered file content when it needs to.

# File lib/js_from_routes/generator.rb, line 116
def write_file_if_changed(name, cache_key)
  FileUtils.mkdir_p(name.dirname)
  cache_key_comment = "// JsFromRoutes CacheKey #{Digest::MD5.hexdigest(cache_key)}\n"
  File.open(name, "a+") { |file|
    if stale?(file, cache_key_comment)
      file.truncate(0)
      file.write(cache_key_comment)
      file.write(yield)
    end
  }
end