【发布时间】:2011-06-30 08:51:00
【问题描述】:
我建立了一个网站,该网站依赖于我目前使用 Nokogiri 解析的 XML 提要。尽管我的管理控制器中当前拥有所有代码,但一切正常且花花公子,因此我实际上可以通过 URL 调用导入,即/admin/import/。
我不禁认为这不属于控制器。有没有更好的方法来做到这一点,即将代码移动到独立的import.rb 文件中,以便只能从控制台访问?如果是这样,我需要把这个文件放在哪里,在/lib/ 目录中?
这是一个代码sn-p:
class AdminController < ApplicationController
def import
f = File.open("#{Rails.root}/public/feed.xml")
@doc = Nokogiri::XML(f)
f.close
ignore_list = [] # ignore list
@doc.xpath("/*/product[not(name = following-sibling::product/name)]").each do |node|
if !ignore_list.include? node.xpath("./programName").inner_text.strip
Product.create(:name => clean_field(node.xpath("./name").inner_text).downcase,
:description => clean_field(node.xpath("./description").inner_text),
:brand => Brand.find_or_create_by_name(clean_field_key(node.xpath("./brand").inner_text).downcase),
:merchant => Merchant.find_or_create_by_name(clean_field_key(node.xpath("./programName").inner_text).downcase),
:image => node.xpath("./imageUrl").inner_text.strip,
:link => node.xpath("./productUrl").inner_text.strip,
:category => Category.find_or_create_by_name(clean_field_key(node.xpath("./CategoryName").inner_text).downcase),
:price => "£" + node.xpath("./price").inner_text.strip)
print clean_field(node.xpath("./name").inner_text).downcase + "\n"
end
end
end
end
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 nokogiri