I created a service object in Rails to work as an interface between our app and our API.
I got the idea from http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/
Here is a small example:
class PackagesService
def self.get_package(package_id)
raise ArgumentError.new("package_id can't be nil") if package_id.blank?
package = API::get "/packages/#{package_id}"
package = JSON.parse package,
:symbolize_names => true unless package.blank?
end
end
Is there any good pattern for handling validation and/or throwing errors for Service objects?
For validations:
- I have to check all the inputs for nil or wrong type. Is there any way for easy validation? Maybe a rails extension?
For errors:
- I could catch all API errors and then safely return a nil. But the programmer using the service object might not know the meaning of nil.
- I could catch the API errors and raise another error which means extra effort to do this in all functions
- Third option is leave it as it is and let the programmer handle all errors from API.
Let me know if you know any good pattern or if you have better ideas to interface an API.