本文介绍了class_eval <<-"end_eval", __FILE__, __LINE__ 在 Ruby 中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何在模块中使用 class_eval(我对 class_eval 有点熟悉)并遇到了 resource_controller 中的这个有用的类.在那里他们有这样的事情:

I'm learning how to use class_eval in modules (I'm somewhat familiar with class_eval) and came across this helpful class in resource_controller. In there they have things like this:

class_eval <<-"end_eval", __FILE__, __LINE__

  def #{block_accessor}(*args, &block)
    unless args.empty? && block.nil?
      args.push block if block_given?
      @#{block_accessor} = [args].flatten
    end

    @#{block_accessor}
  end

end_eval

__FILE____LINE__ 在这种情况下做了什么?我知道 __FILE__ 引用了当前文件,但是这整件事到底做了什么?真的不知道如何搜索:)

What does __FILE__ and __LINE__ do in that context? I know __FILE__ references the current file, but what does that whole thing do exactly? Don't really know how to search for that :).

推荐答案

__FILE____LINE__ 是一种动态常量,用于保存当前正在执行的文件和行.将它们传递到此处允许错误正确报告其位置.

__FILE__ and __LINE__ are sort of dynamic constants that hold the file and line that are currently executing. Passing them in here allow errors to properly report their location.

instance_eval <<-end_eval, __FILE__, __LINE__
  def foo
    a = 123
    b = :abc
    a.send b
  end
end_eval

foo

当你运行这个

$ ruby foo.rb
foo.rb:5:in `send': undefined method `abc' for 123:Fixnum (NoMethodError)
    from foo.rb:5:in `foo'
    from foo.rb:11

注意它说的是文件和第 5 行,即使那只是 eval 中的文本.如果没有这些文件/行技巧,输出将如下所示:

Note it says the file and line #5 even though that was just text in an eval. Without those the file/line trick the output would look like this:

$ ruby foo.rb
(eval):5:in `send': undefined method `abc' for 123:Fixnum (NoMethodError)
    from (eval):5:in `foo'
    from foo.rb:11

堆栈跟踪仅显示 (eval) ,这没有帮助.

The stack trace simply shows (eval) which isn't as helpful.

这篇关于class_eval &lt;&lt;-"end_eval", __FILE__, __LINE__ 在 Ruby 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:48