Ruby继承模块类不起作用

时间:2014-01-27 02:57:40

标签: ruby

我正在尝试在Ruby 2.0.0中编写一个继承自GEXF :: Graph的类“web”,但是我无法使像Web.define_node_attribute这样的Graph方法起作用。我是一个新的红宝石程序员,所以我希望我做的事情很傻。感谢。

webrun.rb

require 'rubygems'
require 'gexf'
require 'anemone'
require 'mechanize'
require_relative 'web'

web = Web.new
web.define_node_attribute(:url)
web.define_node_attribute(:links,    
                            :type => GEXF::Attribute::BOOLEAN,
                            :default => true)

web.rb

require 'rubygems'
require 'gexf'
require 'anemone'
require 'mechanize'

class Web < GEXF::Graph

  attr_accessor :root   
  attr_accessor :pages  

  def initialize
    @pages = Array.new
  end  

  def pages
    @pages
  end  

  def add page
    @pages << page
  end

  def parse uri, protocol = 'http:', domain = 'localhost', file = 'index.html'
    u = uri.split('/')
    if n = /^(https?:)/.match(u[0])
      protocol = n[0] 
      u.shift() 
    end
    if u[0] == ''
      u.shift()
    end
    if n = /([\w\.]+\.(org|com|net))/.match(u[0])
      domain = n[0] 
      u.shift()
    end
    if n = /(.*\.(html?|gif))/.match(u[-1])
      file = n[0] 
      u.pop()  
    end
    cnt = 0
    while u[cnt] == '..' do
      cnt = cnt + 1
      u.shift()
    end 
    while cnt > 0 do
      cnt = cnt - 1
      u.shift()
    end 
    directory = '/'+u.join('/')
    puts "protocol: " + protocol + "   domain: " + domain + \
       "   directory: " + directory  + "   file: " + file 
    protocol + "//" + domain + directory + (directory[-1] == '/' ? '/' : '') + file      
  end

  def crawl
    Anemone.crawl(@root) do |anemone|
      anemone.on_every_page do |sitepage|
        add sitepage
      end
    end
  end    

  def save file    
    f = File.open(file, mode = "w")
    f.write(to_xml)
    f.close()
  end

end  

1 个答案:

答案 0 :(得分:1)

问题是你正在修补GEXF::Graph初始化方法而不调用super。你所做的基本上是“翻转”需要调用的初始化方法。要解决此问题,请更改初始化方法以首先调用super方法:

  def initialize
    super
    @pages = Array.new
  end