我有一个控制器,它显示几个视图,但没有模型支持,这些视图只是从erb渲染为html。
我需要做的是从这些视图中获取在Elasticsearch中建立索引的文本,但是我遇到了相关文档不足的问题。
另一个复杂的因素是视图已翻译,因此它们不直接包含其文本。
我该怎么做才能使这些页面编入索引并可以搜索?既然不能依靠activerecord回调,应该如何维护索引?
基于抓取网站的想法的解决方案:
在WelcomeController中:
format.json { render json: {body:view_to_text(view), title:@title, url:request.original_url.gsub(/\.json$/,'')} }
...
def view_to_text(view)
html = render_to_string view, layout: false, formats: :html
strip_tags(html).strip.gsub(/^[\s]+/,'').squeeze("\n")
end
并在rake任务中:
require 'open-uri'
namespace :scrape do
desc "scrape view content and send to elasticsearch"
task scrape: :environment do
client = Elasticsearch::Model.client
session = ActionDispatch::Integration::Session.new(Rails.application)
session.host! Rails.application.config.action_mailer.default_url_options[:host]
Rails.application.routes.routes.to_a.select{|r| r.defaults[:controller] == 'welcome'}.map{|r| r.path.spec.to_s.gsub( /\(\.\:format\)/, '.json') }.reject{|r| '/'==r}.each_with_index{|path,i|
session.get path
page_string = session.response.body
client.index index: Rails.env, type: 'welcome', id: i, body: page_string
}
end
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句