[英]accessing instance methods inside a ruby/Rails class but outside an instance method
I'm trying to send the count on an active Record object's association to the redis-object gem 我正在尝试将活动Record对象的关联计数发送到redis-object gem
class Post > ActiveRecord::Base
has_many :comments
include Redis::Objects
value :redis_comment_count, :default => self.comments.count
end
PS: setting :default => "string" works just fine PS:设置:default =>“ string”效果很好
but this does not work because self at that place in the code (its not in a method definition) refers to the class definition of Post and not a post instance itself. 但这是行不通的,因为代码中那个位置的self(它不在方法定义中)是指Post的类定义,而不是post实例本身。 I was trying to figure out if this was something that was even possible to do.
我试图弄清楚这是否有可能做到。
Am I making sense? 我说得通吗
Have you tried? 你有没有尝试过?
value :redis_comment_count, default: -> { self.comments.count}
That's using Ruby 1.9's new hash syntax along with the 'stab' or lambda operator . 这使用了Ruby 1.9的新哈希语法以及'stab'或lambda运算符 。
Unfortunately, it looks like you will have to go the longer way of setting up save callbacks for your comments. 不幸的是,您似乎需要为保存评论设置保存回调的方法更长一些。 I browsed through the gem and it doesn't look like passing a proc for calling later is supported yet (see here ).
我浏览了gem,它似乎不支持传递proc以便以后调用(请参阅此处 )。
By the way : 顺便说一句 :
Besides the fact that you are calling the class method and not the instance method, self.comments.count
is evaluated when the class is loaded, right there when you call: 除了您正在调用类方法而不是实例方法的事实之外,在加载类时也会对
self.comments.count
进行评估,即在您调用该方法时:
value :redis_comment_count, :default => self.comments.count
# This becomes:
# value :redis_comment_count, :default => 1 # Example
and not every time that the redis-objects gem uses value_options[:default]
. 并非每次redis-objects gem使用
value_options[:default]
。
This value will keep getting re-evaluated if your class keeps getting reloaded, as in the case of the default setup for the development environment. 如果您的类不断被重载,则该值将不断被重新评估,就像开发环境的默认设置一样。 However, in the production environment where we usually have
cache_classes
enabled, this value will be evaluated only whenever the Rails application boots up and loads your models. 但是,在通常启用了
cache_classes
的生产环境中,仅在Rails应用程序启动并加载模型时才会评估此值。
Passing a proc would work if this were supported. 如果支持,则通过proc将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.