-1
module Powers
 def outer_method name, &block
  puts "outer method works"
   yield 
  end 
 def inner_method name, &block
  puts "inner method works ONLY inside outer method"
  yield 
 end
end 
class Superman
 include Powers 
 def attack 
  outer_method "fly to moon" do 
   inner_method "take a dump" do 
    p "feels good and earth is safe"
   end
  end
  inner_method "take a dump" do 
   p "earth is doomed" 
  end 
 end 
Superman.new.attack

如何强制inner_method只能从outer_method内部的上下文中调用并拯救地球?

4

2 回答 2

1

由于您包含Powers在 中Superman,因此这些Powers方法被视为Superman类的方法,因此没有访问控制会阻止它们被 中的任何其他方法访问Superman,包括inner_method.

于 2013-10-19T20:50:55.113 回答
1

我真的不明白你为什么需要这个。但是这个“黑客”呢?

module Powers
  def outer_method(name, &block)
    puts 'outer method works'
    self.class.send :class_eval, <<-STR, __FILE__, __LINE__
      def inner_method(name, &block)
        puts 'inner method works ONLY inside outer method'
        yield
      end
    STR
    yield
  ensure
    self.class.send(:remove_method, :inner_method) if respond_to?(:inner_method)
  end
end

class Superman
  include Powers

  def attack
    outer_method 'fly to moon' do
      inner_method 'take a dump' do
        p 'feels good and earth is safe'
      end
    end
    inner_method 'take a dump' do
      p 'earth is doomed'
    end
  end
end
于 2013-10-19T21:39:02.860 回答