Reputation: 3476
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 the ActiveRecord classes where I need them?
Thx
Upvotes: 1
Views: 568
Reputation: 16844
There are a few ways do to it, but generally I stick to the following principles.
/lib
(if you have a lot, you may create a /lib/clients
sub dir)GeonamesClient
or GeonamesWrapper
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
Upvotes: 1