2013-07-20 179 views
-1

我想以這種方式來使用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)

+0

在這裏你不需要它,但可能看看'alias_method_chain'反正 –

回答

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"