十一 16

ruby for rails 摘录

模块没有实例,模块被混含在类中。这样类的实例可以调用定义在模块中的实例方法。混含操作由 include 语句实现。require 或 load 时,加载的内容放在引号里。但是使用 include 时,不使用引号。

module Stacklike
  attr_reader :stack

  def initialize
    @stack = Array.new
  end

  def add_to_stack(obj)
    @stack.push(obj)
  end

  def take_from_stack
    @stack.pop
  end
end
require "stacklike"
class CargoHold
  include Stacklike

  def load_and_report(obj)
    pust obj.object_id
    add_to_stack(obj)
  end

  def unload
    take_from_stack
  end
end

使用名称作为类名,使用形容词作为模块的名。上面的例子演示了如何进一步发挥模块的作用。

当给对象发送它不理解的消息的时候,会触发内建方法 method_missing 调用。

class Bicycle
  attr_reader :gears, :wheels, :seats

  def initialize(gears = 1)
    @wheels = 2
    @seats = 1
    @gears = gears
  end
end

class Tandem < Bicycle
  def initialize(gears)
    super
    @seats = 2
  end
end

以super提升方法查找路径。以裸词的方式调用时,自动向前传递调用 super 的发给你发所获得的参数。这个是默认滴。用空参数表调用 super() 时,不给上一级方法传递任何参数,即使是当前方法的谙熟也不传递。用特定参数 super(a, b, c) 时,传递这些指定的参数。

  • 标签 :  ,
  • 原文链接 : http://railser.cn/blog/ruby-for-rails-3
  • 转载原创文章请注明 : 里克的自习室
  • 收藏到 : Google书签 新浪ViVi 365Key网摘 天极网摘 我摘 POCO网摘 博采网摘 YouNote网摘 和讯网摘 博拉网 igooi网摘 I2Key网摘 天下图摘 百特门网摘 Del.icio.us Yahoo书签 奇贴 QQ娱乐摘 添加到Digg! 添加到Facebook!
  • 发表留言