Ruby on Rails全局类变量在更改时不更新

时间:2015-12-11 17:58:17

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

我想为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

我已将我的实现放在名为faye_extension.rb的config / initializers中的新文件中。我添加到代码中的部分是@@ 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 +1代码在incoming()里面不是正确引用或更新我的全局变量。

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

1 个答案:

答案 0 :(得分:2)

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

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