1
尋找有關如何解決此錯誤的建議,並重構此代碼以改進它。模塊中的機械化,Nameerror'agent'
require 'mechanize'
require 'pry'
require 'pp'
module Mymodule
class WebBot
agent = Mechanize.new { |agent|
agent.user_agent_alias = 'Windows Chrome'
}
def form(response)
require "addressable/uri"
require "addressable/template"
template = Addressable::Template.new("http://www.domain.com/{?query*}")
url = template.expand({"query" => response}).to_s
page = agent.get(url)
end
def get_products
products = []
page.search("datatable").search('tr').each do |row|
begin
product = row.search('td')[1].text
rescue => e
p e.message
end
products << product
end
products
end
end
end
調用模塊:
response = {size: "SM", color: "BLUE"}
t = Mymodule::WebBot.new
t.form(response)
t.get_products
錯誤:
NameError: undefined local variable or method `agent'
儘管名稱錯誤,而不是語法錯誤。 – pguardiario
是的。完全正確。我要解決它。 –
工程,很好,謝謝。有關清理代碼的任何建議? – user2012677