博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

include,extend,class_eval的用法 --1

Posted on 2010-04-08 11:00  Watir  阅读(425)  评论(0编辑  收藏  举报

# Case 1

# Simple case of a class having an instance method and a class method class Person def self.count 21 end def name "Neeraj" end end puts Person.count puts Person.new.name
---------------------------------------------------------------------

# Case 2

# A class includes a module to have an instance method
module PersonName
  def name
    "Neeraj"
  end
end

class Person
  def self.count
    21
  end
  include PersonName
end

puts Person.count
puts Person.new.name
---------------------------------------------------------------------

# Case 3

# A module with self.method doesn't become a class method as 
# it might seem on the surface
module PersonModule
  def name
    "Neeraj"
  end
  def self.count
    21
  end
end

class Person
  include PersonModule
end
puts Person.new.name
# Following operation does not work. Exception message is undefined 
# method `count' for Person:Class (NoMethodError)
puts Person.count 
---------------------------------------------------------------------

# Case 4

# Including a module and thus creating a class method is a bit tricky. 
# Simpler solutions are  presented in next versions.
module PersonModule
  def self.included(base_class)
    base_class.extend(ClassMethods)
  end

  def name
      "Neeraj"
  end

   module ClassMethods
    def count
      21
    end
  end
end
class Person
  include PersonModule
end
puts Person.new.name
puts Person.count