我正在编写一个Ruby Gem,其中有一个名为Connection
的模块用于Faraday
配置
module Example
module Connection
private
def connection
Faraday.new(url: 'http://localhost:3000/api') do |conn|
conn.request :url_encoded # form-encode POST params
conn.response :logger # log requests to STDOUT
conn.adapter Faraday.default_adapter # make requests with Net::HTTP
conn.use Faraday::Response::ParseJson
conn.use FaradayMiddleware::RaiseHttpException
end
end
end
end
第二个模块用于进行API请求,代码如下:
module Example
module Request
include Connection
def get(uri)
connection.get(uri).body
end
def post(url, attributes)
response = connection.post(url) do |request|
request.body = attributes.to_json
end
end
def self.extended(base)
base.include(InstanceMethods)
end
module InstanceMethods
include Connection
def put(url, attributes)
response = connection.put(url) do |request|
request.body = attributes.to_json
end
end
end
end
end
我使用Request
的Customer
类如下:
module Example
class Customer
extend Request
attr_accessor :id, :name, :age
def initialize(attrs)
attrs.each do |key, value|
instance_variable_set("@#{key}", value)
end
end
def self.all
customers = get('v1/customer')
customers.map { |cust| new cust }
end
def save
params = {
id: self.id,
age: self.age
name: self.name,
}
put("v1/customers/#{self.id}", params)
end
end
end
在这里,你可以看到在Customer#all
类方法中,我调用了Request#get
方法,这是因为我在Customer
中扩展了Request
。然后我在Request
模块中使用了self.extended方法,使Request#put
在Customer
类中可用。那么,这种使用mixin的方式是否好,或者你有什么建议呢?
Customer.all
接口,您必须在某个时候将连接绑定到类上(这可能比值得的努力更费力,因此混合方法可能会使事情变得更简单)。 - Josh Bodah