REST API for Android clients has been established and used by Rails.
Our service's payment method is basically regular payment. The payment is made at the time of the first purchase, and the user raises the count on the Purchase and sends the payment request again at a certain time.
In order to implement this, it is implemented in the Purchase model as follows
class Purchase << ActiveRecord::Base
validate :request_payment, if: :is_payday?
def request_payment
response = PaymentService.purchase(...)
if response.success?
...
else
body = JSON.parse(response.body)
errors.add(:wallet, body['message'])
end
end
def is_payday?
...
end
end
The problem I want to solve is 1. I feel uncomfortable about the payment request from the validation team (although it is not actual validation, I am dealing with it in validate because the role of the model is too big, so I want to take it out as a service object or observe it).
I can't think of a good solution, so I'm asking for your help
ruby-on-rails active-record refactoring
You can process the payment in before_save as follows, and if an error occurs, add an error to errors, and return false.
class Purchase << ActiveRecord::Base
before_save :request_payment, if: :is_payday?
def request_payment
begin
PaymentService.purchase(...)
rescue => e
errors.add (:base, "payment error")
return false
end
true
end
def is_payday?
...
end
end
I think it would be better to explicitly call the controller than to make a payment request through callback from the model.
Also, rather than parsing the response and processing the error in the request_payment method, I would like you to process it within PaymentService.purchase and treat it as an exception if there is an error.
© 2024 OneMinuteCode. All rights reserved.