where do I implement calls to external clients in rails app
I am writing a rails app, which makes calls to several external web APIs, for instance Geonnames. My idea is to capture this logic in separate modules or classes and call them from my model and controller classes. Are there any best practices where to place such code? Should it be a separate non-ActiveRecord model class or a module in the lib folder? Or is it better to simply implement WS calls as static methods in 开发者_Go百科the ActiveRecord classes where I need them?
Thx
There are a few ways do to it, but generally I stick to the following principles.
- They live in
/lib
(if you have a lot, you may create a/lib/clients
sub dir) - They have names like
GeonamesClient
orGeonamesWrapper
- They are a class you have to instantiate
- They may inherit from a base class (or perhaps mixin some base functionality)
- HTTParty is often a good way to go
An Example;
class ClientBase
# maybe we pass in a logger, or something
def initialize(options={})
end
# perhaps a central way to call the api
def call(method_name, *args)
end
end
class GeonamesClient < ClientBase
base_uri "www.geonames.org"
def postal_codes(country)
...
end
end
You then instantiate it, and call it. (its possible that the client may maintain some state between calls)
client = GeonamesClient.new(:logger => Address.logger)
client.countries.each do |country|
client.postal_codes(country)
end
精彩评论