|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require "dry/effects" |
| 4 | +require "dry/core/class_attributes" |
| 5 | +require "dry/core/memoizable" |
| 6 | + |
| 7 | +require "rom/constants" |
| 8 | +require "rom/initializer" |
| 9 | +require "rom/types" |
| 10 | + |
| 11 | +module ROM |
| 12 | + module Components |
| 13 | + # Abstract component class |
| 14 | + # |
| 15 | + # @api public |
| 16 | + class Core |
| 17 | + extend Initializer |
| 18 | + extend Dry::Core::ClassAttributes |
| 19 | + |
| 20 | + include Dry::Core::Memoizable |
| 21 | + include Dry::Effects.Reader(:configuration) |
| 22 | + |
| 23 | + defines :id |
| 24 | + |
| 25 | + # @!attribute [r] constant |
| 26 | + # @return [Class] Component's target class |
| 27 | + # @api public |
| 28 | + option :constant, optional: true, type: Types.Interface(:new) |
| 29 | + alias_method :relation, :constant |
| 30 | + |
| 31 | + # This method is meant to return a run-time component instance |
| 32 | + # |
| 33 | + # @api public |
| 34 | + def build(**) |
| 35 | + raise NotImplementedError |
| 36 | + end |
| 37 | + |
| 38 | + # @api public |
| 39 | + def trigger(event, payload) |
| 40 | + notifications.trigger("configuration.#{event}", payload) |
| 41 | + end |
| 42 | + |
| 43 | + # @api public |
| 44 | + def relations |
| 45 | + configuration.relations |
| 46 | + end |
| 47 | + |
| 48 | + # @api public |
| 49 | + def command_compiler |
| 50 | + configuration.command_compiler |
| 51 | + end |
| 52 | + |
| 53 | + # @api public |
| 54 | + def notifications |
| 55 | + configuration.notifications |
| 56 | + end |
| 57 | + |
| 58 | + # @api public |
| 59 | + def gateways |
| 60 | + configuration.gateways |
| 61 | + end |
| 62 | + |
| 63 | + # @api public |
| 64 | + def components |
| 65 | + configuration.components |
| 66 | + end |
| 67 | + |
| 68 | + # @api public |
| 69 | + def adapter |
| 70 | + relation.adapter or raise( |
| 71 | + MissingAdapterIdentifierError, "+#{constant}+ is missing the adapter identifier" |
| 72 | + ) |
| 73 | + end |
| 74 | + |
| 75 | + # @api public |
| 76 | + def apply_plugins |
| 77 | + plugins.each do |plugin| |
| 78 | + plugin.apply_to(constant) |
| 79 | + end |
| 80 | + end |
| 81 | + |
| 82 | + # @api public |
| 83 | + memoize def plugins |
| 84 | + configuration.plugins.select { |plugin| plugin.type == self.class.id } |
| 85 | + end |
| 86 | + |
| 87 | + # @api public |
| 88 | + memoize def plugin_options |
| 89 | + plugins.map(&:config).map(&:to_hash).reduce(:merge) || EMPTY_HASH |
| 90 | + end |
| 91 | + |
| 92 | + private |
| 93 | + |
| 94 | + # @api private |
| 95 | + def gateway |
| 96 | + gateways.fetch(gateway_name) do |
| 97 | + raise "+#{gateway_name.inspect}+ gateway not found for #{constant}" |
| 98 | + end |
| 99 | + end |
| 100 | + |
| 101 | + # @api private |
| 102 | + def gateway_name |
| 103 | + relation.gateway |
| 104 | + end |
| 105 | + end |
| 106 | + end |
| 107 | +end |
0 commit comments