我在rake任务中获得了以下代码:
class PdfExporter < ActionView::Base
include Rails.application.routes.url_helpers
include ActionView::Helpers::TagHelper
include ActionView::Helpers::UrlHelper
def generate_pdf_from_html
content = File.read('path/to/view.html.erb')
erb = ERB.new(content)
html_content = erb.result(binding)
# ... some pdf stuff
end
end
问题 - 所述view.html.erb正在渲染另一个视图。
<%= render partial: 'path/to/another_view' %>
erb.result(binding)
引发了以下错误:
缺少部分/路径/到/ another_view
如果没有部分,视图呈现正常。
我确定路径是正确的,但似乎我无法通过rake任务渲染它。
为什么呢?我可以加一些有用的助手吗?
我不想实例化控制器。
编辑:
Searched in:
是空的。可能意味着ActionView不知道&#39;在哪里搜索视图。
答案 0 :(得分:3)
这是我有一个rake任务的例子,它从视图中创建一个html文件。要使它工作,你必须通过覆盖一些默认值并传入一个假的控制器并请求来安抚ActionView:
desc 'Example of writing a view to a file'
task :example => :environment do
# View that works with Rake
class RakeActionView < ActionView::Base
include Rails.application.routes.url_helpers
include ::ApplicationHelper
# Include other helpers that you will use
# Make sure this matches the expected environment, e.g. localhost for dev
# and full domain for prod
def default_url_options
{host: 'localhost:3000'}
end
# It is safe to assume that the rake request is legit
def protect_against_forgery?
false
end
end
# build a simple controller to process the view
controller = ActionController::Base.new
controller.class_eval do
include Rails.application.routes.url_helpers
include ::ApplicationHelper
end
# build a fake request
controller.request = ActionDispatch::TestRequest.new
# build the rake view with the path to the app views
view = RakeActionView.new(Rails.root.join('app', 'views'), {}, controller)
# example assigning instance @variables to the view
view.assign( :user => User.first )
# Render the view to html
html = view.render(template: 'relative/path/to/template', layout: 'layouts/example')
# Write html to temp file and then copy to destination
temp = Tempfile.new('example_file')
temp.write(html)
FileUtils.cp( temp.path, 'path/to/exmple_file' )
# optionally set permissions on file
File.chmod(0774, 'path/to/exmple_file')
# close up the temp file
temp.close
temp.unlink
end
看起来您遇到的问题由RakeActionView.new(Rails.root.join('app', 'views'), {}, controller)
修复,它设置了ActionView查找模板的路径。