你可以在 Rails 中将 self 传递给 lambda 吗? [英] can you pass self to lambda in rails?
问题描述
我想定义一个可以访问局部变量的类方法.因此,对于类的每个实例,这将是不同的.我知道您可以使用 lambda 使类方法动态化,就像将它与 named_scope 一起使用一样.但是对于特定于实例的值可以这样做吗?
I want to define a class method that has access to a local variable. So this would be different for each instance of the class. I know you can make a class method dynamic with lambda like when you use it with named_scope. But can this be done for values that are specific to an instance?
详细来说就是rails中paperclip插件的has_attached_file方法.我想为样式散列传递一个 lambda,以便图像样式可以基于存储在数据库中的对象的属性.这可能吗?
In detail it is the has_attached_file method for the paperclip plugin in rails. I want to pass a lambda for the styles hash so that the image styles can be based off of attributes of the object stored in the DB. Is this possible?
推荐答案
免责声明: 首先,问题(Can you pass self to lambda?)和你遇到的问题'正在尝试解决(带有回形针的动态样式)不完全匹配.我不会回答最初的问题,因为它与您的问题并不完全相关,并且ramion 勇敢地进行了尝试.
Disclaimer: First, the question (Can you pass self to lambda?) and the problem you're trying to solve (dynamic styles with paperclip) don't fully match up. I won't answer the original question because it's not entirely related to your problem, and rampion took a valiant stab at it.
我来回答你的回形针问题.
具体是rails中的回形针插件的has_attached_file
方法.我想为样式散列传递一个 lambda,以便图像样式可以基于存储在数据库中的对象的属性.这可能吗?
In detail it is the
has_attached_file
method for the paperclip plugin in rails. I want to pass a lambda for the styles hash so that the image styles can be based off of attributes of the object stored in the DB. Is this possible?
是的,这是可能的.在回形针中,:styles
选项可以采用 Proc.初始化附件时,如果使用了 Proc,则附件本身将传递给 Proc.附件包含对关联 ActiveRecord 对象的引用,因此您可以使用它来确定您的动态样式.
Yes, it is possible. In paperclip, the :styles
option can take a Proc. When the attachment is initialized, if a Proc was used, the attachment itself is passed to the Proc. The attachment has a reference to the associated ActiveRecord object, so you can use that to determine your dynamic styles.
例如,您的 has_attached_file
声明可能如下所示(假设用户和头像场景,用户可以自定义其头像的大小):
For example, your has_attached_file
declaration might look something like this (assuming a User and avatar scenario where the user can customize the size of their avatar):
class User < ActiveRecord::Base
has_attached_file :avatar, :styles => lambda { |attachment|
user = attachment.instance
dimensions = "#{user.avatar_width}x#{user.avatar_height}#"
{ :custom => dimensions }
}
end
这篇关于你可以在 Rails 中将 self 传递给 lambda 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!