如何继承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模块。
发布于 2020-05-11 18:37:57
如果唯一的目的是设置默认值,而不是重新定义方法,那么下面的操作就会奏效:
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之前添加到祖先堆栈中。当调用由SuperClient和HTTParty定义的方法时,将首先调用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发布于 2020-05-09 06:00:56
您可以将SuperClient保持为类,并从它继承其他客户端。就像这样。两个标题'Auth‘和’X‘都将包含在请求中。
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()https://stackoverflow.com/questions/61629353
复制相似问题