【问题标题】:How to use rails routes in external classes?如何在外部类中使用 Rails 路线?
【发布时间】:2010-05-27 15:37:55
【问题描述】:
我用大虾生成pdf,设置alahttps://github.com/prawnpdf/prawn/wiki
我想访问我的路线,以便在我的 pdf 中生成链接,但现在我不像以前使用 prawnto 那样使用模板,所以我无法访问指定的路线。
class MyPdf < Prawn::Document
def to_pdf
text root_path
end
end
如何包含我的命名路线?
【问题讨论】:
标签:
ruby-on-rails
pdf
url-routing
prawn
【解决方案1】:
你应该include ActionController::UrlWriter
如果你尝试使用来自外部 Rails 环境的命名路由,那么你应该加载环境,但是这个加载会很慢
#If Rails environment is not loaded, be sure you include config/boot.rb correctly
require File.dirname(__FILE__) + 'root_to_your_boot_rb_file'
require RAILS_ROOT + '/config/environment'
include ActionController::UrlWriter
【解决方案2】:
如果你的 Rails 4 应用中有一个独立的类,你可以在这个类中插入以下内容:
include Rails.application.routes.url_helper