Ruby 使用 extend 做装饰模式 ,有没有办法退回上一层

shewer · November 05, 2018 · Last by victor replied at November 08, 2018 · 1336 hits

如题 当我把 module B 及 C extendi 后
有没有方法拆掉 module C 谢谢

module B
   def name
         "B"  + super
    end  
end

module C
    def name
        "C" + super
    end
end
class A
    def  name
          "A"
    end

end
if __FILE__ == $0
   a= A.new
  puts a.name  #=> "A"
  puts  a.singleton_class.ancestors  # => [#<Class:#<A>0x00007fffd913a138>>, B, A, Object, PP::ObjectMixin, Kernel, BasicObject]

 a.extend(B)
 puts  a.name           # =>  "BA"
 puts  a.singleton_class.ancestors  # => [#<Class:#<A>0x00007fffd913a138>>, B, A, Object, PP::ObjectMixin, Kernel, BasicObject]

 a.extend(C)  
 puts  a.name         # => "CBA" 
 puts  a.singleton_class.ancestors  # => [#<Class:#<A>0x00007fffd913a138>> ,C, B, A, Object, PP::ObjectMixin, Kernel, BasicObject]

end

不能。除非你用 evil_ruby 的办法

再 extend B 就好了(待考证)

没有用,已经 extend 的 module 直接跳过 顺序不变 ( 和 module include 一样,已经载入的 module 不会再载入且顺序不变) 仍然是 C -> B -> A

You need to Sign in before reply, if you don't have an account, please Sign up first.