Module: Ekylibre::Record::Bookkeep::ClassMethods

Defined in:
lib/ekylibre/record/bookkeep.rb

Instance Method Summary collapse

Instance Method Details

#bookkeep(options = {}, &block) ⇒ Object

Raises:

  • (ArgumentError)

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
# File 'lib/ekylibre/record/bookkeep.rb', line 75

def bookkeep(options = {}, &block)
  raise ArgumentError, 'No given block' unless block_given?
  raise ArgumentError, "Wrong number of arguments (#{block.arity} for 1)" unless block.arity == 1
  configuration = { on: Ekylibre::Record::Bookkeep.actions, column: :accounted_at, method_name: __method__ }
  configuration.update(options) if options.is_a?(Hash)
  configuration[:column] = configuration[:column].to_s
  method_name = configuration[:method_name].to_s
  core_method_name ||= "_#{method_name}_#{Ekylibre::Record::Bookkeep::Base.next_id}"

  unless columns_definition[configuration[:column]]
    Rails.logger.fatal "#{configuration[:column]} is needed for #{name}::bookkeep"
    # raise StandardError, "#{configuration[:column]} is needed for #{self.name}::bookkeep"
  end

  code = "include Ekylibre::Record::Bookkeep::InstanceMethods\n"

  code << "def #{method_name}(action = :create, draft = nil)\n"
  code << "  draft = ::Preference[:bookkeep_in_draft] if draft.nil?\n"
  code << "  self.#{core_method_name}(Ekylibre::Record::Bookkeep::Base.new(self, action, draft))\n"
  code << "  self.class.where(id: self.id).update_all(#{configuration[:column]}: Time.zone.now)\n"
  code << "end\n"

  configuration[:on] = [configuration[:on]].flatten
  for action in Ekylibre::Record::Bookkeep.actions
    next unless configuration[:on].include? action
    code << "after_#{action} do \n"
    code << "  if ::Preference[:bookkeep_automatically]\n"
    code << "    self.#{method_name}(:#{action}, ::Preference[:bookkeep_in_draft])\n"
    code << "  end\n"
    code << "end\n"
  end

  class_eval code

  send(:define_method, core_method_name, &block)
end