Ruby on rails 模块内机械化,名称错误';代理人';
正在寻找有关如何修复此错误并重构此代码以改进它的建议Ruby on rails 模块内机械化,名称错误';代理人';,ruby-on-rails,ruby,ruby-on-rails-4,mechanize,mechanize-ruby,Ruby On Rails,Ruby,Ruby On Rails 4,Mechanize,Mechanize Ruby,正在寻找有关如何修复此错误并重构此代码以改进它的建议 require 'mechanize' require 'pry' require 'pp' module Mymodule class WebBot agent = Mechanize.new { |agent| agent.user_agent_alias = 'Windows Chrome' } def form(response) require "address
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
错误:
Ruby有一个命名约定<代码>代理是类范围中的局部变量。要使它对其他方法可见,您应该将它命名为类变量
@@agent
,它将在WebBot
的所有对象之间共享。不过,首选的方法是将其命名为@agent
,使其成为实例变量。WebBot
的每个对象都有自己的@agent
。但是你应该把它放在initialize
中,当你用new
创建一个新对象时,将调用initialize
class WebBot
def initialize
@agent = Mechanize.new do |a|
a.user_agent_alias = 'Windows Chrome'
end
end
.....
同样的错误也会出现在页面上。您在表单中将其定义为局部变量。当表单
完成执行时,它将被删除。您应该将其设置为实例变量。幸运的是,您不必将其放入初始化。您可以在表单中定义它。调用表单
后,对象将拥有自己的@页面
。以格式执行此操作
:
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
请记住,每次出现page
和agent
时,都要将@page
和@agent
。在您的获取产品中,例如:
def get_products
products = []
@page.search("datatable").search('tr').each do |row|
.....
这些更改将解决名称错误。重构是另一回事。是的。完全正确。我会修好的,很好,谢谢。关于清理代码有什么建议吗?
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|
.....