2

我对 ruby​​ 和 rails 很陌生。我正在尝试将所有解析的 whois 信息输出到 json 输出。我有以下内容:

class WhoisController < ApplicationController
  def index
    c = Whois::Client.new
    record = c.lookup("google.com")
    parser = record.parser
    created = parser.created_on
    msg = {:created => created}
    render :json => msg
  end
end

输出:

{"created":"1997-09-15T00:00:00.000-07:00"}

但是,解析器有更多可用信息......在不知道所有可用字段的情况下,如何将所有键/值转储到 json?

我试过了:

class WhoisController < ApplicationController
  def index
    c = Whois::Client.new
    record = c.lookup("google.com")
    parser = record.parser
    msg = {:whois => parser}
    render :json => msg
  end
end

但最终得到:

SystemStackError in WhoisController#index

编辑:

我也试过:

parser.attributes.each do |attr_name, attr_value|
  puts attr_name
end

但最终得到另一个错误:

undefined method `attributes' for #<Whois::Parser:0x00007fc030d74018>

Python 和 Go(通过反射)都可以做到这一点。实现这一目标的 Ruby 方法是什么?

编辑:

class WhoisController < ApplicationController
    def index
        c = Whois::Client.new
        record = c.lookup("google.com")
        parser = record.parser
        msg = {}
        for x_prop in Whois::Parser::PROPERTIES
            msg[x_prop] = parser.send(x_prop)
        end
        render :json => msg
    end
end

这仅在解析器上存在所有属性时才有效。但是,某些域名不具备所有属性,会导致:

Unable to find a parser for property `registrant_contacts'

然后我尝试仅在该属性存在时设置它:

msg = {}
for x_prop in Whois::Parser::PROPERTIES
  parser.has_attribute?(:x_prop) 
    msg[x_prop] = parser.send(x_prop) 
end
render :json => msg

我得到另一个错误:

undefined method `has_attribute?'

编辑#3:

我也试过:

msg = {}
for prop in Whois::Parser::PROPERTIES
  msg[prop] = parser.send(prop) if parser.respond_to?(prop)
end
render :json => msg

如果解析器中缺少该属性,这仍然会失败。;(

4

3 回答 3

2
class WhoisController < ApplicationController
    def index
        c = Whois::Client.new
        record = c.lookup("google.com")
        parser = record.parser
        msg = {}
        for x_prop in Whois::Parser::PROPERTIES
            msg[x_prop] = parser.send(x_prop)
        end
        render :json => msg
    end
end

在少数情况下,某些属性可能为空并导致错误,以逃避这一点:

begin
    msg[x_prop] = parser.send(x_prop)
rescue
    # do nothing
end
于 2019-02-03T07:22:31.227 回答
0

对于SystemStackError in WhoisController#index

我认为这是因为您whois再次与 Whois通话record = Whois.whois("google.com")。试试record = whois("google.com")

For undefined method `attributes' for #<Whois::Parser:0x00007fc030d74018>: attributes 方法不会为 whois 解析器退出。请参阅https://whoisrb.org/docs/v3/parser-properties/

于 2019-02-02T18:00:48.253 回答
-2

您可以使用methodsinspect

    c = Whois::Client.new
    record = c.lookup("google.com")
    parser = record.parser
    render json: parser.methods.to_json
    render json: parser.inspect.to_json
于 2019-02-03T02:18:31.607 回答