我创建了小API库,一切都很好,直到我意识到我需要多个配置。
看起来是这样的:
module Store
class Api
class << self
attr_accessor :configuration
def configure
self.configuration ||= Configuration.new
yield configuration
end
def get options = {}
url = "#{configuration.domain}/#{options[:resource]}"
# ResClient url ...
end
end
end
class Configuration
attr_accessor :domain
def initialize options = {}
@domain = options[:domain]
end
end
class Product
def self.get
sleep 5
Api.get resource: 'products'
end
end
end当我同时运行它时,它会覆盖模块配置。
Thread.new do
10.times do
Store::Api.configure do |c|
c.domain = "apple2.com"
end
p Store::Product.get
end
end
10.times do
Store::Api.configure do |c|
c.domain = "apple.com"
end
p Store::Product.get
end我搞不懂如何让这个模块更好。谢谢你的建议
发布于 2013-09-22 23:27:17
好吧,如果你不想让多个线程来争夺一个资源,你就不应该把它变成一个单例。尝试将对象配置从类移动到其实例,然后分别实例化和配置它们。
这里还有更多要重构的地方,但这解决了您的问题:
module Store
class API
attr_reader :domain
def initialize(options = {})
@domain = options[:domain]
end
def products
sleep 5
get resource: 'products'
end
private
def get(options = {})
url = "#{configuration.domain}/#{options[:resource]}"
# ResClient url ...
end
end
end
Thread.new do
10.times do
api = Store::API.new(domain: 'apple2.com')
p api.products
end
end
10.times do
api = Store::API.new(domain: 'apple.com')
p api.products
endhttps://stackoverflow.com/questions/18949662
复制相似问题