Skip to content

Commit

Permalink
fix active model *_previously_changed? dirty methods to accept kwargs
Browse files Browse the repository at this point in the history
since Rails 6.1 they accept kwargs `from` and `to`, see
rails/rails@a6841c7
  • Loading branch information
doits authored and shioyama committed Mar 31, 2024
1 parent f73cd20 commit ffbb3ed
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
8 changes: 5 additions & 3 deletions lib/mobility/plugins/active_model/dirty.rb
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def define_handler_methods
public_patterns.each do |pattern|
method_name = pattern % 'attribute'

kwargs = pattern == '%s_changed?' ? ', **kwargs' : ''
kwargs = (pattern == '%s_changed?' || pattern == '%s_previously_changed?') ? ', **kwargs' : ''
module_eval <<-EOM, __FILE__, __LINE__ + 1
def #{method_name}(attr_name, *rest#{kwargs})
if (mutations_from_mobility.attribute_changed?(attr_name) ||
Expand Down Expand Up @@ -298,8 +298,10 @@ def attribute_changed?(attr_name, from: OPTION_NOT_GIVEN, to: OPTION_NOT_GIVEN)
(OPTION_NOT_GIVEN == to || fetch_value(attr_name) == to)
end

def attribute_previously_changed?(attr_name)
previous_changes.include?(attr_name)
def attribute_previously_changed?(attr_name, from: OPTION_NOT_GIVEN, to: OPTION_NOT_GIVEN)
previous_changes.include?(attr_name) &&
(OPTION_NOT_GIVEN == from || attribute_previous_change(attr_name).first == from) &&
(OPTION_NOT_GIVEN == to || attribute_previous_change(attr_name).second == to)
end

def attribute_was(attr_name)
Expand Down
4 changes: 4 additions & 0 deletions spec/mobility/plugins/active_model/dirty_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -240,10 +240,14 @@ def save
expect(instance.attribute_changed?(:title_en)).to eq(false)

expect(instance.title_previously_changed?).to eq(true)
expect(instance.title_previously_changed?(from: 'foo', to: 'bar')).to eq(true)
expect(instance.title_previously_changed?(from: 'foo', to: 'baz')).to eq(false)
expect(instance.title_previous_change).to eq(["foo", "bar"])
expect(instance.title_changed?).to eq(false)

expect(instance.attribute_previously_changed?(:title_en)).to eq(true)
expect(instance.attribute_previously_changed?(:title_en, from: 'foo', to: 'bar')).to eq(true)
expect(instance.attribute_previously_changed?(:title_en, from: 'foo', to: 'baz')).to eq(false)
expect(instance.attribute_changed?(:title_en)).to eq(false)

expect(instance.title_previously_was).to eq('foo')
Expand Down

0 comments on commit ffbb3ed

Please sign in to comment.