Module: PriceHubble::Client::Utils::Response
- Extended by:
- ActiveSupport::Concern
- Included in:
- Base
- Defined in:
- lib/price_hubble/client/utils/response.rb
Overview
Some helpers to work with responses in a general way.
rubocop:disable Metrics/BlockLength because of ActiveSupport::Concern
Instance Method Summary collapse
-
#assign_entity(entity, res, &block) ⇒ Proc
Perform the assignment of the response to the given entity.
-
#bang_entity(entity, res, data) ⇒ Proc
Perform a common error handling for entity responses.
-
#failed?(res, code: 400..600) ⇒ Boolean
A simple syntactic sugar helper to query the response status.
-
#status?(res, code: 0..399) ⇒ Boolean
(also: #successful?)
Simple helper to query the response status.
Instance Method Details
#assign_entity(entity, res, &block) ⇒ Proc
Perform the assignment of the response to the given entity. This allows a clean usage of the decision flow control for successful requests. Here comes an example:
decision do |result|
result.good(&assign_entity(entity, res))
end
70 71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/price_hubble/client/utils/response.rb', line 70 def assign_entity(entity, res, &block) lambda do entity.assign_attributes(res.body.to_h) entity.send(:changes_applied) # We need to call +#changed?+ - the +@mutations_from_database+ is # unset and this causes issues on subsequent calls to +#changed?+ # after a freeze (eg. when deleted) entity.changed? yield(entity) if block entity end end |
#bang_entity(entity, res, data) ⇒ Proc
Perform a common error handling for entity responses. This allows a clean usage of the decision flow control. Here comes an example:
decision do |result|
result.bang(&bang_entity(entity, res, id: entity.id))
end
46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/price_hubble/client/utils/response.rb', line 46 def bang_entity(entity, res, data) class_name = entity class_name = entity.class unless entity.is_a? Class lambda do next PriceHubble::EntityNotFound.new(nil, class_name, data) \ if res.status == 404 next PriceHubble::EntityInvalid.new(res.body., entity) \ if res.status == 400 PriceHubble::RequestError.new(nil, res) end end |
#failed?(res, code: 400..600) ⇒ Boolean
A simple syntactic sugar helper to query the response status.
31 32 33 |
# File 'lib/price_hubble/client/utils/response.rb', line 31 def failed?(res, code: 400..600) status?(res, code: code) end |
#status?(res, code: 0..399) ⇒ Boolean Also known as: successful?
Simple helper to query the response status.
19 20 21 22 23 |
# File 'lib/price_hubble/client/utils/response.rb', line 19 def status?(res, code: 0..399) code = [code] unless code.is_a? Range code = code.flatten if code.is_a? Array code.include? res.status end |