Skip to content

Commit

Permalink
Add new functionality for querying, filtering, and sorting changes
Browse files Browse the repository at this point in the history
  • Loading branch information
exAspArk committed Apr 26, 2024
1 parent c6d180c commit 394ae52
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/bemi.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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"
33 changes: 33 additions & 0 deletions lib/bemi/change_query_helpers.rb
Original file line number Diff line number Diff line change
@@ -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
24 changes: 24 additions & 0 deletions lib/bemi/record_query_helpers.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 394ae52

Please sign in to comment.