Skip to content

Commit

Permalink
chore(relation): adjust actable and belongs_to
Browse files Browse the repository at this point in the history
- starting Ruby 3, use **options instead of options = {}
- include adjustable scope to define actable
- no longer support ActiveRecord below 6
- touch -> self.touch to differentiate function and boolean value
  • Loading branch information
bivanalhar authored and cysjonathan committed Jul 24, 2024
1 parent 3a37d43 commit 784f4f8
Showing 1 changed file with 11 additions and 9 deletions.
20 changes: 11 additions & 9 deletions lib/active_record/acts_as/relation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ def acts_as(name, scope = nil, options = {})
as = options.delete(:as) || :actable
validates_actable = !options.key?(:validates_actable) || options.delete(:validates_actable)

options = options.reverse_merge(as: as, validate: false, inverse_of: as)

reflections = has_one(name, scope, **options)
reflections = has_one(name, scope, **options.reverse_merge(as: as,
validate: false,
inverse_of: as))
default_scope -> {
case association_method
when :eager_load
Expand All @@ -28,7 +28,7 @@ def acts_as(name, scope = nil, options = {})
validate :actable_must_be_valid if validates_actable

before_save do
@_acting_as_changed = ActiveRecord.version.to_s.to_f >= 5.1 ? acting_as.has_changes_to_save? : acting_as.changed?
@_acting_as_changed = acting_as.has_changes_to_save?
true
end
after_commit do
Expand All @@ -54,10 +54,10 @@ def acts_as(name, scope = nil, options = {})

after_update do
non_cyclic_save(acting_as) do
if ActiveRecord.version.to_s.to_f >= 5.1 ? acting_as.has_changes_to_save? : acting_as.changed?
if acting_as.has_changes_to_save?
acting_as.save
elsif touch != false
touch
self.touch if saved_changes?
end
end
end
Expand All @@ -83,10 +83,12 @@ def is_a?(klass)
super || acting_as?(klass)
end

def actable(options = {})
def actable(scope = nil, **options)
name = options.delete(:as) || :actable

reflections = belongs_to(name, **options.reverse_merge(validate: false, polymorphic: true, dependent: :destroy))
reflections = belongs_to(name, scope, **options.reverse_merge(validate: false,
polymorphic: true,
dependent: :destroy))

cattr_reader(:actable_reflection) { reflections.stringify_keys[name.to_s] }

Expand All @@ -108,7 +110,7 @@ def self.scope(*)
include ActsAs::Autosave
after_update do
non_cyclic_save(actable) do
if ActiveRecord.version.to_s.to_f >= 5.1 ? actable.has_changes_to_save? : actable.changed?
if actable.has_changes_to_save?
actable.save
end
end
Expand Down

0 comments on commit 784f4f8

Please sign in to comment.