在不使用eval的情况下动态检查JSON中的字段是否为nil

时间:2015-01-11 13:27:07

标签: ruby json eval

以下是我正在使用的代码的摘录:

def retrieve(user_token, quote_id, check="quotes")
  end_time = Time.now + 15
  match = false
  until Time.now > end_time || match
    @response = http_request.get(quote_get_url(quote_id, user_token))
    eval("match = !JSON.parse(@response.body)#{field(check)}.nil?")
  end
  match.eql?(false) ? nil : @response
end

private

def field (check)
  hash = {"quotes" => '["quotes"][0]',
 "transaction-items" => '["quotes"][0]["links"]["transactionItems"]'
  }
  hash[check]
end

我被告知以这种方式使用eval并不是一种好习惯。有谁能建议一种更好的方法来动态检查JSON节点的存在(字段?)。我希望这样做:

psudo: match = !JSON.parse(@response.body) + dynamic-path + .nil?

1 个答案:

答案 0 :(得分:0)

将路径存储为路径元素数组(['quotes', 0])。有了辅助功能,你就可以避免使用eval。这确实是完全不合适的。

这些方面的东西:

class Hash
  def deep_get(path)
    path.reduce(self) do |memo, path_element|
      return unless memo
      memo[path_element]
    end
  end
end

path = ['quotes', 0]
hash = JSON.parse(response.body)
match = !hash.deep_get(path).nil?