【问题标题】:Why does Ruby not throw an error in an instance where the class name and file name of the class are mismatched?为什么在类的类名和文件名不匹配的情况下Ruby不会抛出错误?
【发布时间】:2019-06-04 01:07:44
【问题描述】:

为什么 Ruby 解释器没有在这个实例中抛出 NameError?

class OrangeTurtle
   self.table_name = 'turtles'
end

文件名:orange_turtles.rb

【问题讨论】:

  • 不熟悉任何强制执行此行为的语言。
  • 您的问题不清楚。在这种情况下,为什么 Ruby raiseNameError?它可以raiseNameError 的唯一原因是Class#table_name 不存在。

标签: ruby-on-rails ruby autoload


【解决方案1】:

这个答案可能听起来像个警察,但它不会引发错误,因为 Ruby 根本不在乎你的文件名是什么。

例如在文件asdfasdf.no_rb_ending_here我们可以有

#!/usr/bin/env ruby
module Something
  class Test
    def test
      puts 'test'
    end
  end
end
class SomethingElse
  def otherThings
    puts 'haha'
  end
end

然后为了让事情变得更奇怪,我可以有一个单独的文件来修改(猴子补丁)该文件中定义的类。 在more_stuff.rb

#!/usr/bin/env ruby
require_relative 'asdfasdf.no_rb_ending_here'
module Something
  class Test
    def test2
      test()
      puts '2'
    end
  end
end
class SomethingElse
  def moreThings
    otherThings()
    puts 'MOAR'
  end
end

Something::Test.new.test2()
# test
# 2
SomethingElse.new.moreThings()
# haha
# MOAR

Ruby 非常酷 - 你不会因为不需要导致错误的事情而出错。

【讨论】:

    【解决方案2】:

    名称错误或未初始化常量错误仅出现在 Rails 中。这样做的原因是,活动记录(这也是一种通用设计模式)正在将数据库中的表与模型(或一般的对象)进行映射。 Active Record 只能通过文件和类的命名约定来建立连接。 正如另一个答案中提到的,纯红宝石不需要遵守这些约定。但是,一般的规则是像它们包含的类一样命名文件,以便更好地组织代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-06
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      相关资源
      最近更新 更多