module的继承

原创
2014/01/15 08:03
阅读数 33

extend(module, ...) → obj 这是Ruby方法,不是Rails方法(注意:常见的include方法也是Ruby方法,不是Rails方法)。 而且extend的是'模块'不能是'类'

extend, include, require这三者中只在‘require’是针对‘文件名’的(后缀一般省略),前二者针对‘模块名’---此外,还有针对文件名的‘load’, 使用机率很小

再者,谁 extend 则 module里的方法就在谁的层面上!例如:

  module Mod
     def hello
       "Hello from Mod.\n"
     end
   end

   class Klass
     def hello
       "Hello from Klass.\n"
     end
   end

   k = Klass.new
   k.hello         #=> "Hello from Klass.\n"
   k.extend(Mod)   #=> #<Klass:0x401b3bc8> # 对象extend
   k.hello         #=> "Hello from Mod.\n"

而这里却是:


1.9.3p0 :006 > class B
1.9.3p0 :007?>   def put_b
1.9.3p0 :008?>     p "i am from b"
1.9.3p0 :009?>     end
1.9.3p0 :010?>   end

1.9.3p0 :012 > module C
1.9.3p0 :013?>   def put_c
1.9.3p0 :014?>     p "from c model"
1.9.3p0 :015?>     end
1.9.3p0 :016?>   end

1.9.3p0 :017 > B.extend C # 类extend

1.9.3p0 :019 > b = B.new
1.9.3p0 :021 > b.put_c
NoMethodError: undefined method `put_c' for #<B:0x8860f6c>

1.9.3p0 :022 > B.put_c
"from c model"

=== 分隔线 ===

require 'make_voteable/voting'
require 'make_voteable/voteable'
require 'make_voteable/voter'
require 'make_voteable/exceptions'

module MakeVoteable
  def voteable?
    false
  end

  def voter?
    false
  end

  # Specify a model as voteable.
  #
  # Example:
  # class Question < ActiveRecord::Base
  #   make_voteable
  # end
  def make_voteable 
    include Voteable
  end

  # Specify a model as voter.
  #
  # Example:
  # class User < ActiveRecord::Base
  #   make_voter
  # end
  def make_voter
    include Voter
  end
end

ActiveRecord::Base.extend MakeVoteable

上面的ActiveRecord::Base.extend MakeVoteable不会继承

require 'make_voteable/voting'
require 'make_voteable/voteable'
require 'make_voteable/voter'
require 'make_voteable/exceptions'

尽管它们也是 moduld MakeVoteable,它们之所以起作用,是因为这里的require
Awsome !

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部