File: fake_middleware.rb

package info (click to toggle)
ruby-web-console 4.2.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 632 kB
  • sloc: ruby: 1,496; javascript: 497; sh: 19; makefile: 4
file content (44 lines) | stat: -rw-r--r-- 1,151 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# frozen_string_literal: true

require "action_view"
require "action_dispatch" # This is needed to use Mime::Type
require "web_console"
require "web_console/testing/helper"

module WebConsole
  module Testing
    class FakeMiddleware
      I18n.load_path.concat(Dir[Helper.gem_root.join("lib/web_console/locales/*.yml")])

      DEFAULT_HEADERS = { Rack::CONTENT_TYPE => "application/javascript" }

      def initialize(opts)
        @headers        = opts.fetch(:headers, DEFAULT_HEADERS)
        @req_path_regex = opts[:req_path_regex]
        @view_path      = opts[:view_path]
      end

      def call(env)
        body = render(req_path(env))
        @headers[Rack::CONTENT_LENGTH] = body.bytesize.to_s

        [ 200, @headers, [ body ] ]
      end

      def view
        @view = View.with_empty_template_cache.with_view_paths(@view_path)
      end

      private

        # extract target path from REQUEST_PATH
        def req_path(env)
          File.basename(env["REQUEST_PATH"].match(@req_path_regex)[1], ".*")
        end

        def render(template)
          view.render(template: template, layout: nil)
        end
    end
  end
end