Module: ControllerRuntime

Defined in:
lib/controller_runtime.rb,
lib/controller_runtime/version.rb,
lib/controller_runtime/runtime_registry.rb

Defined Under Namespace

Modules: RuntimeRegistry

Constant Summary collapse

VERSION =
"0.1.2"

Class Method Summary collapse

Class Method Details

.make_controller_runtime(name, label) ⇒ Object



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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/controller_runtime.rb', line 19

def self.make_controller_runtime(name, label)
  runtime_attr = "#{name.to_s.underscore}_runtime".to_sym
  runtime_attr_setter = "#{name.to_s.underscore}_runtime=".to_sym

  Module.new do
    extend ActiveSupport::Concern

    const_set(:ClassMethods, Module.new do
      define_method :log_process_action do |payload|
        messages = super(payload)
        runtime = payload["#{name}_runtime".to_sym]
        messages << ("#{label}: %.1fms" % runtime.to_f) if runtime
        messages
      end
    end)

    define_method :initialize do |*args|
      super(*args)
      send(runtime_attr_setter, nil)
    end

    private

    attr_internal runtime_attr

    define_method :process_action do |action, *args|
      RuntimeRegistry.reset(name)
      super(action, *args)
    end

    define_method :cleanup_view_runtime do |&block|
      runtime_before_render = RuntimeRegistry.reset(name)
      send(runtime_attr_setter, (send(runtime_attr) || 0.0) + runtime_before_render)
      runtime = super(&block)
      runtime_after_render = RuntimeRegistry.reset(name)
      send(runtime_attr_setter, send(runtime_attr) + runtime_after_render)
      runtime - runtime_after_render
    end

    define_method :append_info_to_payload do |payload|
      super(payload)

      payload["#{name}_runtime".to_sym] = (send(runtime_attr) || 0.0) + RuntimeRegistry.reset(name)
    end
  end
end

.register(name, event:, label: name.to_s.titelize) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/controller_runtime.rb', line 7

def self.register(name, event:, label: name.to_s.titelize)
  runtime_class = make_controller_runtime(name, label)

  ActiveSupport.on_load(:action_controller) do
    include runtime_class
  end

  ActiveSupport::Notifications.monotonic_subscribe(event) do |_name, start, finish, _id, _payload|
    ControllerRuntime::RuntimeRegistry.increment_runtime(name, (finish - start) * 1_000.0)
  end
end