从模块 - ruby​​定义受保护的类方法

时间:2015-02-12 05:10:55

标签: ruby

我试图通过模块为类提供一个受保护的方法,这些模块只能由它自己和继承它们的其他类调用。我想隐藏方法不被Class.method使用,只能在内部访问Class类或继承Class的子类。我该怎么做呢?这是我到目前为止所做的。

#! /usr/bin/env ruby
module ProtectedClassMethods
  @class_instance_var = 1234567

  def included(base); base.extend(ProtectedClassMethods); end

  protected

  def protected_class_method; puts "A PROTECTED CLASS METHOD => #{@class_instance_var}"; end
end

class Class1
  def value; "Class1"; end
end

class Class2 < Class1
  extend ProtectedClassMethods
  class << self
    protected_class_method #crashes here
  end
  def value; "Class2"; end

end

class Class3 < Class2
  class << self
    @class_instance_var = 24681012
    protected_class_method
  end 
  def value; "Class3"; end
end



puts "Initializing Class1"
class1 = Class1.new
puts "Done (Class1)"

puts "Initializing Class2"
class2 = Class2.new
puts "Done (Class2)"

puts "Initializing Class3"
class3 = Class3.new
puts "Done (Class3)"

puts class1.value
puts class2.value
puts class3.value

发出此错误

./protected_class_test.rb:20:in `singletonclass': undefined local variable or method `protected_class_method' for #<Class:Class2> (NameError)
        from ./protected_class_test.rb:18:in `<class:Class2>'
        from ./protected_class_test.rb:16:in `<main>'

1 个答案:

答案 0 :(得分:1)

这是一件有用的工作。

module ProtectedClassMethods
  @class_instance_var = 1234567

  def included(base); base.extend(ProtectedClassMethods); end

  protected

  def protected_class_method; puts "A PROTECTED CLASS METHOD => #{@class_instance_var}"; end
end

class Class1
  def value; "Class1"; end
end

class Class2 < Class1
  extend ProtectedClassMethods
  protected_class_method #crashes here
  def value; "Class2"; end

end

class Class3 < Class2
  @class_instance_var = 24681012
  protected_class_method
  def value; "Class3"; end
end



puts "Initializing Class1"
class1 = Class1.new
puts "Done (Class1)"

否则

class << self
  protected_class_method #crashes here
end

您实际上是在元类(类的类)上调用该方法,并且该方法是在类本身上定义的。