Pergunta

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

How to enforce that the inner_method can ONLY be called from the context inside outer_method and save the planet??

Foi útil?

Solução

I really can't understand why you need this. But what about this "hack"?

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

Outras dicas

Since you're including Powers within Superman, the Powers methods are treated as methods of the Superman class, so there is no access control that will prevent them from being accessible to any other method in Superman, including inner_method.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top