如何允许从ruby中的特定类初始化一个类,并且在其他地方没有?

问题描述 投票:0回答:1
module A
  module B
    class Foo
      def initialize(args)
        @args = args
      end
      def call
        puts 'Inside Foo'
      end
    end
  end
end

module C
  class Boo
    def initialize(args)
      @args = args
    end
    def call
      puts 'Inside Boo'
      A::B::Foo.new(@args).call
    end
  end
end

boo = C::Boo.new(nil).call
# Inside Boo
# Inside Foo

A::B::Foo.new(nil).call
# Inside Foo

如何避免A::B::Foo.new(nil).call?它只能从Boo类访问。

[如果有人想访问Foo类,他们将可以从Boo中访问它。我该如何实现?

搜索过的Internet,但找不到该概念的名称?

ruby-on-rails ruby class module access
1个回答
0
投票

这是红宝石-因此,不存在使对象成为“私有”对象的坚固方法。 (例如,您可以通过.send访问私有方法!)但是您至少可以定义私有interface

但是,从OOP角度看,您的界面实际上没有多大意义。为什么仅在A::B::Foo中可以访问C::Boo?如果A::B::Foo是私有的,则只能在A::B中访问,而不能在其他地方访问。

您正在寻找的关键方法是:private_constant

并且您可以通过使用private_constant规避私有常量查找异常。

因此,我们可以“破解”您当前的实现,使其工作如下:

const_get
© www.soinside.com 2019 - 2024. All rights reserved.