Module: Logisticed::Logisticer::ClassMethods

Defined in:
lib/logisticed/logisticer.rb

Instance Method Summary collapse

Instance Method Details

#logisticed(attr, options = {}) ⇒ Object



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
# File 'lib/logisticed/logisticer.rb', line 11

def logisticed(attr, options = {})
  struct = ListenerStruct.new(self, attr, options)
  has_many :logistics, -> { order(created_at: :asc) },
           as: :source, class_name: Logisticed.logistic_class.name,
           inverse_of: :source

  has_one :logistic, -> { order(created_at: :asc) },
          as: :source, class_name: Logisticed.logistic_class.name,
          inverse_of: :source

  struct.normalize_values.each do |value|
    has_many "#{value}_logistics".to_sym, -> { where(value: value).order(created_at: :asc) }, as: :source, class_name: Logisticed.logistic_class.name, inverse_of: :source
  end

  after_commit do
    if new_value = send("#{attr}_previous_change")&.last.presence
      execute_method_name = "#{attr}_change_to_#{new_value}"
      send(execute_method_name) if respond_to?(execute_method_name)
    end
  end

  class_eval do
    def value_change_by(value)
      logistics.where(value: value).last
    end

    struct.normalize_values.each do |value|
      define_method "#{value}_at" do
        value_change_by(value)&.created_at
      end

      define_method "#{value}_by" do
        value_change_by(value)&.operator
      end

      define_method "#{attr}_change_to_#{value}" do
        logistics.create(value: value)
      end
    end
  end
end