模块方法访问限制

时间:2016-01-27 10:48:40

标签: ruby

我的课程C继承了课程A并包含了模块BA有一个方法baz

class A
  def baz; 5 end
end

module B
  def foobaz; baz end
end

class C < A
  include B
  def barbaz; baz end
end

我想禁止B实例(间接)调用baz,但允许C实例调用baz

B.new.foobaz # => error
C.new.foobaz # => no error
C.new.barbaz # => no error

我该怎么做?

2 个答案:

答案 0 :(得分:0)

也许这就是你想做的事情?

class A
  def baz; 5 end
end

module B
  module_function
  def foobaz
    self.respond_to(:baz) ? baz : "No baz defined :("
  end
end

class C < A
  include B
  def barbaz; baz end
end

B.foobaz # => "No baz defined :("
C.new.foobaz # => 5
C.new.barbaz # => 5

答案 1 :(得分:0)

我的选择:

class A
  private def baz; 5 end
end

module B
  def foobaz; self.baz end
end

class C < A
  include B
  def barbaz; baz end
end

C.new.foobaz # => private method `baz' called
C.new.barbaz # => no error