diff --git a/lib/bemi.rb b/lib/bemi.rb index 8589209..4ec6320 100644 --- a/lib/bemi.rb +++ b/lib/bemi.rb @@ -3,7 +3,9 @@ class Bemi end +require_relative "./bemi/change_query_helpers" require_relative "./bemi/context" require_relative "./bemi/migration" require_relative "./bemi/migration_generator" +require_relative "./bemi/record_query_helpers" require_relative "./bemi/version" diff --git a/lib/bemi/change_query_helpers.rb b/lib/bemi/change_query_helpers.rb new file mode 100644 index 0000000..e128484 --- /dev/null +++ b/lib/bemi/change_query_helpers.rb @@ -0,0 +1,33 @@ +# frozen_string_literal: true + +require 'active_support/concern' + +module Bemi::ChangeQueryHelpers + extend ActiveSupport::Concern + + included do + scope :before, ->(hash) { where('before @> ?', hash.to_json) } + scope :after, ->(hash) { where('after @> ?', hash.to_json) } + scope :context, ->(hash) { where('context @> ?', hash.to_json) } + + scope :created, -> { where(operation: 'CREATE') } + scope :updated, -> { where(operation: 'UPDATE') } + scope :deleted, -> { where(operation: 'DELETE') } + + scope :asc, -> { order(committed_at: :asc) } + scope :desc, -> { order(committed_at: :desc) } + + self.filter_attributes = [] + end + + def diff + result = {} + + (before.keys | after.keys).each do |key| + next if before[key] == after[key] + result[key] = [before[key], after[key]] + end + + result + end +end diff --git a/lib/bemi/record_query_helpers.rb b/lib/bemi/record_query_helpers.rb new file mode 100644 index 0000000..854dbe6 --- /dev/null +++ b/lib/bemi/record_query_helpers.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +require 'active_support/concern' + +module Bemi::RecordQueryHelpers + extend ActiveSupport::Concern + + class_methods do + # Setter + def bemi_change_class(bemi_change_class_name) + @@bemi_change_class_name = bemi_change_class_name + end + + # Getter + def __bemi_change_class + raise "Please set the change class name with `bemi_change_class 'BemiChange'`" if !@@bemi_change_class_name + @@__bemi_change_class ||= @@bemi_change_class_name.constantize + end + end + + def bemi_changes + self.class.__bemi_change_class.where(table: self.class.table_name, primary_key: attributes[self.class.primary_key]) + end +end