[英]How can I add a “method” to this hash?
I'm writing a custom OAuth2 strategy. 我正在编写自定义OAuth2策略。 I need to add an expired?
我需要添加expired?
method to the hash response and I'm not sure how to do it. 哈希响应的方法,我不确定该怎么做。 The response I'm getting gives me a time until expiry but not the expired method itself. 我得到的响应使我有一段时间直到到期,但没有过期的方法本身。
I need to add an expired? 我需要添加过期的吗? method to it, not sure how. 方法,不确定如何。 Any help? 有什么帮助吗?
Instead of using a Hash directly, you could create a new class in build_access_token
that extends it. 您可以在build_access_token
中创建一个新类来扩展它,而不是直接使用Hash。
class AccessToken < Hash
def initialize response_hash
# This overrides the default behavior, you don't care here.
# But if you do, just remove this and call merge manually.
self.merge!(response_hash)
end
def expired?
# return true if expired, false otherwise
end
end
Then, in build_access_token, do something like: 然后,在build_access_token中,执行以下操作:
token = AccessToken.new response_hash
Now, your object is not just Hash
, but your "super-hash" AccessToken
. 现在,您的对象不仅是Hash
,而且是您的“超级哈希” AccessToken
。 You could attach other methods as needed. 您可以根据需要附加其他方法。
Further down the line, you could change this to take a "whitelisting" approach as well, taking a Hash in your constructor, only exposing the elements of that Hash that you want to expose to consumers via methods, and removing the Hash extension. 再往下,您也可以将其更改为采用“白名单”方法,在构造函数中使用哈希,仅将要通过方法公开给消费者的哈希的元素公开,并删除哈希扩展。 But the above should do you for now. 但以上内容现在应该为您做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.