最近我想採取這樣定義霍勒斯·勒布提到rake任務並將其翻譯成一個獨立的背景作業,但不易翻譯。
這是我對Rails 2.3.x的實現,因爲我找到的Rails 3 implementation不起作用。
# Public: Template to render views outside the context of a controller.
#
# Useful for rendering views in rake tasks or background jobs when a
# controller is unavailable.
#
# Examples
#
# template = OfflineTemplate.new(:users)
# template.render("users/index", :layout => false, :locals => { :users => users })
#
# template = OfflineTemplate.new(ProjectsHelper, PermissionsHelper)
# template.render("projects/recent", :projects => recent_projects)
#
class OfflineTemplate
include ActionController::UrlWriter
include ActionController::Helpers::ClassMethods
# Public: Returns the ActionView::Base internal view.
attr_reader :view
# Public: Convenience method to
delegate :render, :to => :view
# Public: Initialize an offline template for the current Rails environment.
#
# helpers - The Rails helpers to include (listed as symbols or modules).
def initialize(*helpers)
helper(helpers + [ApplicationHelper])
@view = ActionView::Base.new(Rails.configuration.view_path, {}, self)
@view.class.send(:include, master_helper_module)
end
private
# Internal: Required to use ActionConroller::Helpers.
#
# Returns a Module to collect helper methods.
def master_helper_module
@master_helper_module ||= Module.new
end
end
這可作爲要點:https://gist.github.com/1386052。
然後你就可以使用上面的類來創建一個OfflineTemplate呈現在rake任務的意見吧:
task :recent_projects => :environment do
template = OfflineTemplate.new(ProjectsHelper, PermissionsHelper)
puts template.render("projects/recent", :projects => recent_projects)
end
這篇文章是有幫助 http://stackoverflow.com/questions/30725119/render-a -re-ra-rake-task – 2015-07-07 16:19:37