继承 HTTParty 模块



如何继承HTTParty模块来设置一些默认值?

module SuperClient
include HTTParty
headers 'Auth' => 'Basic'
end
module ServiceApiClient
include SuperClient
headers 'X-Prop' => 'Some specific data'
base_uri 'https://example.com'
def self.posts
self.get '/posts'
# Expected to send headers Auth and X-Prop
end
end

我需要一些自定义模块,这些模块可以包含在客户端类中,并且表现得像本机HTTParty模块。

如果唯一的目的是设置默认值而不是重新定义方法,则以下内容可以解决问题:

module SuperClient
def self.included(base)
base.include HTTParty
# defaults
base.headers 'Auth' => 'Basic'
# or
base.class_eval do
headers 'Auth' => 'Basic'
end
end
end

当您包含SuperClient时,它将包含HTTParty并设置一些默认值。如果这是您唯一需要的功能,那么如果您还计划重新定义方法,这就是您的答案。


如果您计划重新定义方法,则这不起作用HTTParty将在SuperClient之前添加到祖先堆栈中。当调用由SuperClientHTTParty定义的方法时,将首先调用HTTParty变体,这意味着永远不会到达SuperClient变体。

这可能比您需要的信息更多,但上述问题可以通过执行以下操作来解决:

module SuperClient
def self.included(base)
base.include HTTParty
base.include InstanceMethods
base.extend  ClassMethods
# defaults
# ...
end
module InstanceMethods
# ...
end
module ClassMethods
# ...
end
end

通过包含InstanceMethods并在包含HTTParty后扩展ClassMethods,它们将位于堆栈的较高位置,从而允许您重新定义方法并调用super

class C
include SuperClient
end
# methods are search for from top to bottom
puts C.ancestors
# C
# SuperClient::InstanceMethods
# HTTParty::ModuleInheritableAttributes
# HTTParty
# SuperClient
# Object
# JSON::Ext::Generator::GeneratorMethods::Object
# Kernel
# BasicObject
puts C.singleton_class.ancestors
# #<Class:C>
# SuperClient::ClassMethods
# HTTParty::ModuleInheritableAttributes::ClassMethods
# HTTParty::ClassMethods
# #<Class:Object>
# #<Class:BasicObject>
# Class
# Module
# Object
# JSON::Ext::Generator::GeneratorMethods::Object
# Kernel
# BasicObject

您可以将超级客户端保留为类,并从中继承其他客户端。像这样的东西。标头"Auth"和"X-Prop"都将包含在请求中。

require 'httparty'
class SuperClient 
include HTTParty
headers 'Auth' => 'Basic'
# Uncomment below line to print logs in terminal
# debug_output STDOUT
end
class ServiceApiClient < SuperClient
headers 'X-Prop' => 'Some specific data'
base_uri 'https://example.com'
def posts
self.class.get '/posts'
# Expected to send headers Auth and X-Prop
end
end         
client = ServiceApiClient.new
client.posts()

最新更新