当类名查找静默失败时,`Class.new`返回`nil`?

时间:2015-11-17 11:25:34

标签: ruby pry

这是我尝试从类方法中实例化的类:
请注意,没有initializenew,并且两者都是从Base继承的

module Operation
  module ExampleOperation
    class Read < SkinnyControllers::Operation::Base
      def run
        model if allowed?
      end
    end
  end
end

这是我的pry输出:

From: /home/me/Development/skinny_controllers/lib/skinny_controllers/operation/base.rb @ line 24 SkinnyControllers::Operation::Base.run:

    21: def self.run(current_user, params)
    22:   object = self.new(current_user, params)
    23:   binding.pry
 => 24:   object.run
    25: end

[1] pry(Operation::ExampleOperation::Read)> object
=> nil
[2] pry(Operation::ExampleOperation::Read)> self
=> Operation::ExampleOperation::Read
[3] pry(Operation::ExampleOperation::Read)> self.new
=> nil
[4] pry(Operation::ExampleOperation::Read)> Operation::ExampleOperation::Read.new
NameError: uninitialized constant SkinnyControllers::Operation::ExampleOperation
from (pry):4:in `run'

# Try the top level namespace just in case
[5] pry(Operation::ExampleOperation::Read)> ::Operation::ExampleOperation::Read.new
=> nil


# see if I can instantiate the base class
[6] pry(Operation::ExampleOperation::Read)> SkinnyControllers::Operation::Base.new(User.new, {})
=> #<SkinnyControllers::Operation::Base:0x0000000117e7a0 @authorized_via_parent=false, @current_user=#<User:0x0000000117e7f0>, @params={}>

# try instantiate via specifying the exact namespace shown in line 4
[7] pry(Operation::ExampleOperation::Read)> SkinnyControllers::Operation::ExampleOperation::Read.new(User.new, {})
NameError: uninitialized constant SkinnyControllers::Operation::ExampleOperation
from (pry):7:in `run'

为什么会发生这种情况? self.new 没有制作实例对象真的很奇怪。

这是我的代码,可以看到失败的测试: at this specific commit

我读到newinitialize之间的关系,认为这是不可能的。也许我在SkinnyControllers::OperationOperation的分辨率之间有一些时髦的东西,但我想记录下来并收集其他人的想法。

更新:

initialize方法仅在超类Operation::Base

中定义
  def initialize(current_user, params)
    self.current_user = current_user
    self.params = params
    self.authorized_via_parent = false
  end

0 个答案:

没有答案