如何扩展模块,覆盖方法,仍然调用重写方法?

时间:2013-07-20 04:13:58

标签: ruby

我想以这种方式使用URI:

require 'open-uri'
uri = URI.parse('http://subdomain.domain.com/section/page.html')
puts uri.first_level_domain # => 'domain.com'

我该怎么做?

我正在尝试:

module URI
    def parse
        ret = super
        domain = ret.host.split('.').last(2).join('.')
        ret.send(:define_method, :first_level_domain, lambda { domain })        
        ret
    end
end

但我得到undefined method 'first_level_domain' for #<URI::HTTP:0x9bc7ab0> (NoMethodError)

1 个答案:

答案 0 :(得分:3)

为什么这么复杂?你可以这样的

module URI
  def first_level_domain
    host.split('.').last(2).join('.')
  end
end

uri = URI.parse('http://subdomain.domain.com/section/page.html')
uri.first_level_domain
# => "domain.com"
相关问题