开发者

where do I implement calls to external clients in rails app

开发者 https://www.devze.com 2023-04-11 06:29 出处:网络
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 contro

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.

  1. They live in /lib (if you have a lot, you may create a /lib/clients sub dir)
  2. They have names like GeonamesClient or GeonamesWrapper
  3. They are a class you have to instantiate
  4. They may inherit from a base class (or perhaps mixin some base functionality)
  5. 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号