Class: Twig::RailsRenderer

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.environmentObject



43
44
45
46
47
48
49
50
51
52
# File 'lib/twig/railtie.rb', line 43

def self.environment
  options = {
    cache: Rails.root.join('tmp/cache/twig').to_s,
    debug: Rails.env.development?,
  }

  @environment ||= ::Twig::Environment.new(loader, options).tap do |env|
    env.add_extension(::Twig::Extension::Rails.new)
  end
end

.loaderObject



36
37
38
39
40
41
# File 'lib/twig/railtie.rb', line 36

def self.loader
  @loader ||= ::Twig::Loader::Filesystem.new(
    Rails.root,
    %w[/ /app/views]
  )
end

Instance Method Details

#call(template, source) ⇒ Object



5
6
7
8
9
10
11
12
13
14
# File 'lib/twig/railtie.rb', line 5

def call(template, source)
  <<~TEMPLATE
    ::#{self.class.name}.
      environment.
      load_template("#{template.short_identifier}", call_context: self, output_buffer: @output_buffer).
        render(local_assigns)

    @output_buffer
  TEMPLATE
end

#translate_location(spot, backtrace_location, source) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/twig/railtie.rb', line 16

def translate_location(spot, backtrace_location, source)
  template = backtrace_location.path.delete_prefix(Rails.root.to_s)

  # Attempt to recompile the template to find where the syntax error is
  # otherwise just do what would have happened anyway
  begin
    self.class.environment.render_ruby(template)
  rescue ::Twig::Error::Syntax => e
    return spot.merge({
      first_lineno: e.lineno,
      last_lineno: e.lineno + 1,
      script_lines: source.lines,
    })
  rescue StandardError
    # Nothing, don't add another exception to the problem
  end

  spot
end