我已经在我的 Rails 应用程序中安装了来自 github.com 的acts_as_versioned 插件,并且有一个我不完全理解的代码块,我希望有人能为我解决这个问题
class_eval <<-CLASS_METHODS
def a_bunch_of_stuff
....
end
CLASS_METHODS
我知道该块内的方法(或不管它是什么)被定义为类内部的实例方法,但我在插件中的任何地方都找不到定义为常量的 CLASS_METHODS,而且我也不确定 class_eval 之后的 <<- 意味着什么。 该插件位于 此处,相关代码从 lib/ 的第 199 行开始acts_as_versioned.rb。 如果有人愿意告诉我这里的内幕,我将非常感激。
谢谢
-C
I have installed the acts_as_versioned plugin from github.com in my rails application, and there was a block of code that I don't fully understand, I was hoping someone could clear this up for me
class_eval <<-CLASS_METHODS
def a_bunch_of_stuff
....
end
CLASS_METHODS
I get that the methods inside the block (or whatever it is) gets defined as instance methods inside the class, but I can't find CLASS_METHODS defined as a constant anywhere in the plugin, and I'm also not sure what <<- after class_eval means. the plugin is located here, and the code in question starts on line 199 of lib/acts_as_versioned.rb. If someone would give me the lowdown here, I would be much-obliged.
thx
-C
发布评论
评论(3)
这是一个异端邪说。 http://en.wikipedia.org/wiki/Heredoc#Ruby
匹配的 CLASS_METHODS 标记本质上是开始和结束引号。 如果使用 <<- 而不是 <<,则结束标记可以用空格缩进。
您可以在 Ruby 中同时使用多个heredocs(我使我的heredocs与参数名称相同,但这只是为了美观 - 它没有区别):
It's a heredoc. http://en.wikipedia.org/wiki/Heredoc#Ruby
The matched CLASS_METHODS tokens are essentially starting and ending quotes. If you use <<- instead of <<, the ending token can be indented with whitespace.
You can use multiple heredocs at once in Ruby (I made my heredocs the same as the argument names, but that's just for aesthetic - it makes no difference):
这是一个“此处文档”,这是一种内联引用大型多行字符串的方法。 来自 Ruby 编程:
这将导致
class_eval
将CLASS_METHODS
之间的内容视为字符串,并在适当的上下文中执行它。 名称CLASS_METHODS
的使用是任意的,它可以很容易地被称为其他名称。This is a "here document", which is a way of quoting large multiline strings inline. From Programming Ruby:
This will cause
class_eval
to treat the stuff betweenCLASS_METHODS
as a string and execute it in the appropriate context. The use of the nameCLASS_METHODS
is arbitrary, it could just as easily have been called anything else.这些是等效的:
These are equivalent: