【问题标题】:Ruby on Rails Global Class Variable not updating when changedRuby on Rails 全局类变量在更改时不更新
【发布时间】:2015-12-11 17:58:17
【问题描述】:

我想为 ruby​​ gem 中的类添加一个小扩展。

我使用的 gem 是 private_pub:https://github.com/ryanb/private_pub,而我覆盖的类是:https://github.com/ryanb/private_pub/blob/master/lib/private_pub/faye_extension.rb

我已将我的实现放在 config/initializers 中名为 faye_extension.rb 的新文件中。我添加到代码中的部分是 @@clients 和 get_list_of_subscribers 类方法。 faye_extension.rb 中的代码如下:

PrivatePub::FayeExtension
module PrivatePub
  # This class is an extension for the Faye::RackAdapter.
  # It is used inside of PrivatePub.faye_app.
  class FayeExtension
    # Callback to handle incoming Faye messages. This authenticates both
    # subscribe and publish calls.

#####  MY NEW BIT
    @@clients = 0
    def self.get_list_of_subscribers
      @@clients
    end

####


    def incoming(message, callback)
    @@clients = @@clients + 1
      if message["channel"] == "/meta/subscribe"
        authenticate_subscribe(message)
      elsif message["channel"] !~ %r{^/meta/}
        authenticate_publish(message)
      end
      callback.call(message)
    end

  private

    # Ensure the subscription signature is correct and that it has not expired.
    def authenticate_subscribe(message)
      subscription = PrivatePub.subscription(:channel => message["subscription"], :timestamp => message["ext"]["private_pub_timestamp"])
      if message["ext"]["private_pub_signature"] != subscription[:signature]
        message["error"] = "Incorrect signature."
      elsif PrivatePub.signature_expired? message["ext"]["private_pub_timestamp"].to_i
        message["error"] = "Signature has expired."
      end
    end

    # Ensures the secret token is correct before publishing.
    def authenticate_publish(message)
      if PrivatePub.config[:secret_token].nil?
        raise Error, "No secret_token config set, ensure private_pub.yml is loaded properly."
      elsif message["ext"]["private_pub_token"] != PrivatePub.config[:secret_token]
        message["error"] = "Incorrect token."
      else
        message["ext"]["private_pub_token"] = nil
      end
    end
  end
end

当部署到我的应用程序中时,FayeExtension 代码的incoming() 方法会被多次调用,但是如果在某个视图中我使用以下代码行:

<h3><%= PrivatePub::FayeExtension.get_list_of_subscribers.to_s %></h3>

调用我的 get_list_of_subscribers 类方法,它总是返回 0,尽管我调用了 incoming() 5 次,我希望它输出 5。所以看起来我的 @@clients = @@clients +1incoming() 代码没有引用或正确更新我的全局变量。

如何更改代码以实现此目的?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 scope faye


    【解决方案1】:

    @@clients 可能是一个类变量,但它不会在不同进程之间共享。部署到生产环境的应用程序通常运行多个进程。

    您需要将该值存储在每个进程都可以访问的位置:您的数据库、redis、memcache...

    【讨论】:

      猜你喜欢
      • 2022-01-16
      • 1970-01-01
      • 2014-01-31
      • 2017-07-04
      • 1970-01-01
      • 1970-01-01
      • 2017-07-19
      • 2018-01-21
      • 1970-01-01
      相关资源
      最近更新 更多