首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >改进模块结构

问改进模块结构
EN

Stack Overflow用户
提问于 2013-09-22 23:03:13
回答 1查看 118关注 0票数 0

我创建了小API库,一切都很好,直到我意识到我需要多个配置。

看起来是这样的:

代码语言:javascript
复制
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

当我同时运行它时,它会覆盖模块配置。

代码语言:javascript
复制
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

我搞不懂如何让这个模块更好。谢谢你的建议

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-22 23:27:17

好吧,如果你不想让多个线程来争夺一个资源,你就不应该把它变成一个单例。尝试将对象配置从类移动到其实例,然后分别实例化和配置它们。

这里还有更多要重构的地方,但这解决了您的问题:

代码语言:javascript
复制
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
end
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18949662

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档