代码之家  ›  专栏  ›  技术社区  ›  zotherstupidguy

Ruby DSL:需要严格的方法可见性技术

  •  -1
  • zotherstupidguy  · 技术社区  · 11 年前
    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内部的上下文中调用,并拯救地球??

    2 回复  |  直到 11 年前
        1
  •  1
  •   DarkDemiurge    11 年前

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

    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
    
        2
  •  1
  •   Peter Alfvin    11 年前

    既然你包括 Powers 在内部 Superman 这个 权力 方法被视为 超人 类,因此没有访问控制来阻止中的任何其他方法访问它们 超人 包括…在内 inner_method .