开发重新加载后,Rails singleton变空了

时间:2016-09-14 19:29:36

标签: ruby-on-rails singleton

在我的rails应用程序中,我决定使用singleton创建某种工厂来正确获取对象。

配置/初始化/ registry.rb:

registry = Registry.instance

registry.define_lazy :period_predictor do
  PeriodPredictor.new(NotificationBuilder.new, 28, 4, 3)
end

registry.define_lazy :notification_sender do
  NotificationSender.new
end

LIB / registry.rb:

# Registry class which is singleton and stores values.
class Registry
  include Singleton


  # Define simple value. Like a constant.
  #
  # @param key [Symbol]
  # @param value
  def define(key, value)
    container[key] = value
  end


  # Define value (block required) which will be calculated when it will be need.
  # It will calculate it every time when it will be needed.
  #
  # @param key [Symbol]
  # @param block [Proc]
  def define_lazy(key, &block)
    container[key] = LazyValue.new(&block)
  end


  # Get value.
  #
  # @param key [Symbol]
  #
  # @return
  def get(key)
    value = container[key]
    if value.is_a?(LazyValue)
      value = value.call
    end

    value
  end


  # Get value (hash access).
  #
  # @param key [Symbol]
  #
  # @return
  def [](key)
    get(key)
  end


  # Export all the values.
  # Replacing values of returned hash won't change registry.
  #
  # @return [Hash]
  def export
    container.clone
  end


  # Import hash data to registry
  #
  # @param data [Hash]
  def import(data)
    data.each do |key, value|
      @container[key] = value
    end
  end


  private

  # Get container.
  #
  # @return [Hash]
  def container
    @container ||= {}
  end


  # Class to store lazy value.
  class LazyValue
    def initialize(&block)
      @block = block
    end

    def call
      @block.call
    end
  end
end

生产中的一切都很好。但是当我改变某些东西(甚至在某处添加空间)时,我无法再从控制器中获取单例数据。

Registry.instance成为了注册表的新鲜实例 Registry.instance [:period_predictor]变为零

当我离开单身并制作类方法时,会发生同样的事情。

只有在关闭单例并创建常量时才会执行此操作:

registry = Registry.new

registry.define_lazy :period_predictor do
  PeriodPredictor.new(NotificationBuilder.new, 28, 4, 3)
end

registry.define_lazy :notification_sender do
  NotificationSender.new
end

REGISTRY = registry

Rails版本4.2.5.1

有人知道为什么会这样吗?

1 个答案:

答案 0 :(得分:4)

我已经发现,它发生了,因为Rails刷新了自动加载的常量。 http://guides.rubyonrails.org/autoloading_and_reloading_constants.html#constant-reloading

我添加了行要求"#{Rails.root} / lib / registry"在初始化程序的开始,一切都很好。