Skip to content

Commit

Permalink
Add reload callbacks
Browse files Browse the repository at this point in the history
This commit introduces three additional callbacks:

* `before_reload` - evaluated before re-fetching the resource's data
  with a `GET` request

* `after_reload` - evaluated after re-fetching the resource's data with
  a `GET` request

* `around_reload` - evaluated around re-fetching the resource's data
  with a `GET` request
  • Loading branch information
seanpdoyle committed Jan 5, 2025
1 parent 9c8a2ee commit 9ce3898
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
4 changes: 3 additions & 1 deletion lib/active_resource/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1442,7 +1442,9 @@ def encode(options = {})
# my_branch.reload
# my_branch.name # => "Wilson Road"
def reload
self.load(self.class.find(to_param, params: @prefix_options).attributes, false, true)
run_callbacks :reload do
self.load(self.class.find(to_param, params: @prefix_options).attributes, false, true)
end
end

# A method to manually load attributes from a \hash. Recursively loads collections of
Expand Down
3 changes: 2 additions & 1 deletion lib/active_resource/callbacks.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ module Callbacks

CALLBACKS = [
:before_validation, :after_validation, :before_save, :around_save, :after_save,
:before_reload, :around_reload, :after_reload,
:before_create, :around_create, :after_create, :before_update, :around_update,
:after_update, :before_destroy, :around_destroy, :after_destroy
]
Expand All @@ -16,7 +17,7 @@ module Callbacks
extend ActiveModel::Callbacks
include ActiveModel::Validations::Callbacks

define_model_callbacks :save, :create, :update, :destroy
define_model_callbacks :save, :reload, :create, :update, :destroy
end
end
end
15 changes: 15 additions & 0 deletions test/cases/callbacks_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,21 @@ def test_create
], developer.history
end

def test_reload
developer = Developer.find(1)
developer.reload
assert_equal [
[ :before_reload, :method ],
[ :before_reload, :proc ],
[ :before_reload, :object ],
[ :before_reload, :block ],
[ :after_reload, :method ],
[ :after_reload, :proc ],
[ :after_reload, :object ],
[ :after_reload, :block ]
], developer.history
end

def test_update
developer = Developer.find(1)
developer.save
Expand Down

0 comments on commit 9ce3898

Please sign in to comment.