定义has_rich_text方法时__FILE__和__LINE__ + 1的作用是什么?

时间:2019-03-21 14:10:12

标签: ruby-on-rails ruby

我在Rails中找到了以下代码,但是找不到__FILE____LINE__ + 1的作用。当您在class_eval中定义如下所示的方法时,有人可以解释它们的用途吗?

def has_rich_text(name)
  class_eval <<-CODE, __FILE__, __LINE__ + 1
    def #{name}
      self.rich_text_#{name} ||= ActionText::RichText.new(name: "#{name}", record: self)
    end

    def #{name}=(body)
      self.#{name}.body = body
    end
  CODE

  has_one :"rich_text_#{name}", -> { where(name: name) }, class_name: "ActionText::RichText", as: :record, inverse_of: :record, dependent: :destroy

  scope :"with_rich_text_#{name}", -> { includes("rich_text_#{name}") }
  scope :"with_rich_text_#{name}_and_embeds", -> { includes("rich_text_#{name}": { embeds_attachments: :blob }) }

  after_save do
    public_send(name).save if public_send(name).changed?
  end
end

1 个答案:

答案 0 :(得分:3)

错误报告(回溯)已相应更改:

class Test
  def self.fun_ok(name)
    class_eval <<-CODE, __FILE__, __LINE__ + 1
      def #{name}; raise; end
    CODE
  end

  def self.fun_ko(name)
    class_eval <<-CODE
      def #{name}; raise; end
    CODE
  end
end

让我们创建方法:

Test.fun_ok("ok")
Test.fun_ko("ko")

让我们测试一下

begin
  Test.new.ok
rescue => e
  puts e.backtrace.inspect
end
#⇒ ["/tmp/foo.rb:4:in `ok'", "/tmp/foo.rb:19:in `<main>'"]

begin
  Test.new.ko
rescue => e
  puts e.backtrace.inspect
end
#⇒ ["(eval):1:in `ko'", "/tmp/foo.rb:25:in `<main>'"]

您可能会看到,前一个回溯指向源代码中导致异常的确切行(尤其是"/tmp/foo.rb:4"部分。)后一个指向无处。