开发者

How to use rails routes in external classes?

I'm using prawn to generate pdfs, set up ala https://github.com/prawnpdf/prawn/wiki

I'd like to access my routes so I can generate links in my pdfs, but now I'm not in a template like I used to do with prawnto, so I don't have access to the named route开发者_运维技巧s.

class MyPdf < Prawn::Document
  def to_pdf
    text root_path
  end
end

How can I include my named routes?


You should include ActionController::UrlWriter

And if you are trying to use named routes from outside Rails environment, then you should load the environment, but this loading will be slow

#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


If you have an independent Class inside your Rails 4 app, you can insert the following in this class:

include Rails.application.routes.url_helper
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜