Class: OpenCode::Rails::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/open_code/rails/middleware.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



10
11
12
# File 'lib/open_code/rails/middleware.rb', line 10

def initialize(app)
  @app = app
end

Class Method Details

.loadable?(config) ⇒ Boolean

Returns:

  • (Boolean)


38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/open_code/rails/middleware.rb', line 38

def loadable?(config)
  return false if %w[false off disabled].include?(config.editor)

  dir = Pathname.new(__dir__)
  css = dir.join('vcr.css').read
  defaults = generate_defaults(dir, config.editor, config.place_holder, config.root_dir)
  js = dir.join('vcr.js').read.sub('$$__DEFAULTS__$$', JSON.pretty_generate(defaults))
  self.html_code = <<-HTML.strip_heredoc
    <style id="_open-code-rails_">
    #{css}
    </style>
    <script>
    #{js}
    </script>
  HTML
  true
end

Instance Method Details

#call(env) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/open_code/rails/middleware.rb', line 14

def call(env)
  res = @app.call(env)
  begin
    status, headers, body = res
    return res unless status.to_s == '500' && headers['Content-Type'].to_s.include?('html')

    html = ''
    body.each { |part| html << part }
    body = html.sub('</body>', "#{html_code}</body>").encode('utf-8')
    headers['Content-Length'] = body.size
    [status, headers, [body]]
  rescue => e
    ::Rails.try(:logger)&.error do
      <<-LOG.strip_heredoc
        [OpenCode::Rails::Middleware] #{e.class}: #{e}
          Sorry still something went wrong
          from #{e.backtrace.join("\n  ")}
      LOG
    end
    res
  end
end