Class: LazyGraph::BuilderGroup

Inherits:
Object
  • Object
show all
Defined in:
lib/lazy_graph/builder_group.rb

Class Method Summary collapse

Class Method Details

.bootstrap!(reload_paths: [], listen: ENV['RACK_ENV'] == 'development') ⇒ Object

A builder group is simply a named colleciton of builders (each a subclass of LazyGraph::Builder) That can be reloaded in bulk, and exposed via a simple HTTP server interface.



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
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/lazy_graph/builder_group.rb', line 5

def self.bootstrap!(reload_paths: [], listen: ENV['RACK_ENV'] == 'development')
  reload_paths = Array(reload_paths)
  Module.new do
    define_singleton_method(:included) do |base|
      def base.each_builder(const = self, &blk)
        return to_enum(__method__, const) unless blk

        if const.is_a?(Class) && const < LazyGraph::Builder
          blk[const]
        elsif const.is_a?(Module)
          const.constants.each do |c|
            each_builder(const.const_get(c), &blk)
          end
        end
      end

      def base.server
        LazyGraph::Server.new(
          routes: each_builder.map do |builder|
            [
              builder.to_s.downcase.gsub('::', '/').gsub(/^#{name.downcase}/, ''),
              builder
            ]
          end.to_h
        )
      end

      base.define_singleton_method(:reload_lazy_graphs!) do
        each_builder do |builder|
          builder.clear_rules_modules!
          builder.clear_helper_modules!
        end

        reload_paths.flat_map { |p| Dir[p] }.each do |file|
          load file
        rescue StandardError => e
          LazyGraph.logger.error("Failed to load #{file}: #{e.message}")
        end
      end

      base.reload_lazy_graphs!

      return unless listen

      require 'listen'
      Listen.to(*reload_paths.map { |p| p.gsub(%r{(?:/\*\*)*/\*\.rb}, '') }) do
        base.reload_lazy_graphs!
      end.start
    end
  end
end