繁体   English   中英

Ruby继承模块类不起作用

[英]Ruby inheriting a module class not working

我正在尝试在Ruby 2.0.0中编写一个继承自GEXF :: Graph的类“ web”,但无法使Graph方法(如Web.define_node_attribute)正常工作。 我是一个新的ruby程序员,所以我希望自己正在做一些愚蠢的事情。 谢谢。

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  

问题是您正在猴子修补GEXF::Graph初始化方法,而没有对其调用super。 您所做的基本上是“覆盖”需要调用的initialize方法。 要解决此问题,请将您的initialize方法更改为首先调用super方法:

  def initialize
    super
    @pages = Array.new
  end  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM