Module: Roda::RodaPlugins::DebugBar

Defined in:
lib/roda/plugins/debug_bar.rb

Defined Under Namespace

Modules: InstanceMethods

Constant Summary collapse

DEFAULTS =
{
  db: nil,
  log_time: false,
  trace_missed: true,
  ##### PUT TRACE ALL TO TRUE AGAIN
  trace_all: false,
  # trace_all: true,
  filtered_params: %w[password password_confirmation _csrf],
  handlers: [:console]
}.freeze

Class Method Summary collapse

Class Method Details

.configure(app, opts = {}) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/roda/plugins/debug_bar.rb', line 36

def self.configure(app, opts = {})
  # app.opts[:debug_bar] = opts

  @@data_store = []

  options = DEFAULTS.merge(opts)

  logger = TTY::Logger.new { |config|
    config.handlers = options[:handlers]
    config.output = options.fetch(:output) { File.open('/dev/null', 'w') }
    config..push(:time, :date) if options[:log_time]
    config.filters.data = options[:filtered_params]
    config.filters.mask = "<FILTERED>"
  }

  root = Pathname(app.opts[:root] || Dir.pwd)

  db = options[:db] || (defined?(DB) && DB)
  db&.extension :debug_bar

  ::Sequel::Model.plugin :debug_bar

  app.match_hook do
    callee = caller_locations.find { |location|
      location.path.start_with?(root.to_s)
    }

    @_debug_bar_instance.add_match(callee)
  end

  app.before do
    @_debug_bar_instance = Roda::DebugBar::Instance.new(logger, env, object_id, root, options[:filter])

    @halted = false

    if request.path == '/debug_bar/ruby.png'
      @halted = true
      response.status = 200
      response['content-type'] = 'image/png'
      response.write(File.open(File.join(__dir__, '../../../public/ruby.png')).read)
      request.halt
    end

    if request.path == '/debug_bar/out.css'
      @halted = true
      response.status = 200
      response['content-type'] = 'text/css'
      response.write(File.open(File.join(__dir__, '../../../public/out.css')).read)
      request.halt
    end

    if request.path.start_with? '/debug_bar/last/'
      @halted = true
      id = request.path.split('/').last.to_i

      if id > @@data_store.size
        response.status = 404
        response['content-type'] = 'text/plain'
        response.write "Log ##{id} either doesn't exist yet, or wasn't stored. The current max store is 5."
        request.halt
      end

      response.status = 200
      response['content-type'] = 'application/json'
      response.write(@@data_store[-id].to_json)
      request.halt
    end

    # request.env['PATH_INFO'] is Rack's raw path
    # request.path is a Roda abstraction over it, but can't be modified
    @debug_catch = false
    if request.env['PATH_INFO'].start_with? '/debug_bar/catch/'
      @debug_catch = true
      request.env['PATH_INFO'].sub!('/debug_bar/catch', '')
    end
    if request.env['PATH_INFO'].start_with? '/debug_bar/c/'
      @debug_catch = true
      request.env['PATH_INFO'].sub!('/debug_bar/c', '')
    end
    if request.env['PATH_INFO'].start_with? '/c/'
      @debug_catch = true
      request.env['PATH_INFO'].sub!('/c', '')
    end

  end

  app.after do |res|

    break if @halted

    status, headers, content = res
    @_debug_bar_instance.add(
      status,
      request,
      (options[:trace_missed] && status == 404) || options[:trace_all]
    )

    # This @data is available to views
    @data = @_debug_bar_instance.debug_data

    if @debug_catch
      response = @data.to_json
      res[1]['content-type'] = 'application/json'
      res[1]['Content-Length'] = response.bytesize.to_s
      res[2] = [response]
      @_debug_bar_instance.drain
      @_debug_bar_instance.reset
      break
    end

    if headers['content-type'] == 'text/html'
      #####

      # Should be a method, but I'm having trouble accessing the class variable from within an instance method
      # def add_data(data)
        if @@data_store.size < 5
          @@data_store << @data
        else
          @@data_store.shift
          @@data_store.push @data
        end
      # end

      #####

      # add_data(@data)

      puts @@data_store.size
    end

    imports = <<-HTML
  <script src="https://unpkg.com/[email protected]/dist/cdn.min.js" defer></script>
  <!-- <script src="https://raw.githubusercontent.com/caldwell/renderjson/refs/heads/master/renderjson.js"></script>
  <script src="https://cdn.jsdelivr.net/gh/caldwell/renderjson@master/renderjson.js"></script>
  <script defer src="https://unpkg.com/pretty-json-custom-element/index.js"></script>
  <script src="https://unpkg.com/@alenaksu/[email protected]/dist/json-viewer.bundle.js"></script> -->
HTML

    if headers['content-type'] == 'text/html'

      res[2] = res[2].map do |body_part|
        if body_part.include?("<head>")
          body_part.sub("<head>", "<head>#{imports}")
        else
          "#{imports}#{body_part}"
        end
      end

      debug_bar = relative_render('debug_bar')

      res[2] = res[2].map do |body_part|
        if body_part.include?("</body>")
          body_part.sub("</body>", "#{debug_bar}</body>")
        else
          "#{body_part}#{debug_bar}"
        end
      end

      res[1]["Content-Length"] = res[2].reduce(0) { |memo, chunk| memo + chunk.bytesize }.to_s

    end

    # if request.path == '/baz'
    #   puts 'hi hi hi'
    # end

    @_debug_bar_instance.drain
    @_debug_bar_instance.reset
  end
end

.load_dependencies(app, opts = {}) ⇒ Object



26
27
28
29
30
31
32
33
34
# File 'lib/roda/plugins/debug_bar.rb', line 26

def self.load_dependencies(app, opts = {})
  app.plugin :render

  # just to display sessions
  # app.plugin :sessions, secret: 'very-secret'*20

  app.plugin :hooks
  app.plugin :match_hook
end