Skip to content

Commit

Permalink
Fixed an error in Ruby 3 when specifying a method that takes keyword …
Browse files Browse the repository at this point in the history
…arguments, such as event's before hook. (#777)

* Reproduction case added

* Allow keyword arguments to be passed to event before, etc. in Ruby 2.7.1 and above.

* refactoring
  • Loading branch information
pocari committed Apr 14, 2022
1 parent 72d7860 commit 018c3a9
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
15 changes: 14 additions & 1 deletion lib/aasm/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,20 @@ def safely_define_method(klass, method_name, method_definition)
end
end

klass.send(:define_method, method_name, method_definition)
klass.send(:define_method, method_name, method_definition).tap do |sym|
apply_ruby2_keyword(klass, sym)
end
end

def apply_ruby2_keyword(klass, sym)
if RUBY_VERSION >= '2.7.1'
if klass.instance_method(sym).parameters.find { |type, _| type.to_s.start_with?('rest') }
# If there is a place where you are receiving in *args, do ruby2_keywords.
klass.module_eval do
ruby2_keywords sym
end
end
end
end

def namespace?
Expand Down
16 changes: 16 additions & 0 deletions spec/models/event_with_keyword_arguments.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class EventWithKeywordArguments
include AASM

aasm do
state :open, :initial => true, :column => :status
state :closed

event :close do
before :_before_close
transitions from: :open, to: :closed
end
end

def _before_close(key:)
end
end
10 changes: 10 additions & 0 deletions spec/unit/event_with_keyword_arguments_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
require 'spec_helper'

describe EventWithKeywordArguments do
let(:example) { EventWithKeywordArguments.new }
describe 'enable keyword arguments' do
it 'should be executed correctly that method registered by "before hooks" for events with keyword arguments.' do
expect(example.close(key: 1)).to be_truthy
end
end
end

0 comments on commit 018c3a9

Please sign in to comment.