1

基本クラスのインスタンス メソッドから、保護されたスーパークラス クラス メソッドを呼び出したいと考えています。

class A
  class << self
    protected
    def foo
      puts "In foo"
    end
  end
end

class B < A
  def bar
    puts "In bar"
    # call A::foo
  end
end

これを行う最善の方法は何ですか?

4

4 に答える 4

3

... 2.67年後 ...

これを解決する簡単な方法は、class_eval を使用することです

class A
  class << self
    protected
    def foo
      puts "In foo"
    end
  end
end

class B < A
  def bar
    self.class.class_eval { foo }
  end
end

B.new.bar    # prints "In foo"
于 2012-09-17T04:17:05.203 に答える
1

スーパーを呼び出して、Bのメソッドをオーバーライドします。

class A
  class << self
    protected
    def foo
      puts "In foo"
    end
  end
end

class B < A

  def self.foo
    super
  end

  def bar
    puts "In bar"
    # call A::foo
    self.class.foo        
  end
end

>> B.foo
=> In foo
>> B.new.bar
=> In bar
=> In foo
于 2010-12-01T03:52:05.710 に答える
0

私はおそらく A.foo を公開するだけです。それ以外の場合sendは、アクセス制御をバイパスするため、実行されます。

A.send(:foo)
于 2010-12-01T03:27:17.880 に答える
0

これまでのところ、私が見つけた唯一の解決策は、スーパークラスのクラス メソッドを呼び出すサブクラスのクラス メソッドを定義することです。次に、サブクラスのインスタンス メソッドでこのメソッドを呼び出すことができます。

class A
  class << self
    protected
    def foo
      puts "In foo"
    end
  end
end

class B < A
  def self.call_foo
    puts "In call_foo"
    A::foo
  end

  def bar
    puts "In bar"
    self.class.call_foo
  end
end

これは本当に必要ですか?

于 2010-12-01T02:39:39.927 に答える