在 lib 文件夹模块中使用 url_for [英] using url_for in a lib folder module

查看:44
本文介绍了在 lib 文件夹模块中使用 url_for的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,其中包含一个名为type"的字段和一个名为value"的字段.type 字段将决定在渲染之前如何解析值".我希望这很容易扩展,所以我在我的 lib 文件夹中放置了各种格式化程序"类.

I have a model with a field called "type" and a field called "value". The type field will determine how the "value" is parsed before rendering. I want this to be easily extendible, so I'm putting a variety of "formatter" classes in my lib folder.

我的一个格式化程序"调用了 url_for:

One of my "formatters" has a call to url_for:

class CustomTypeFormatter 
  include ActionView::Helpers::TextHelper
  include ActionView::Helpers

  def show
    raw sanitize( auto_link( value ) )
  end

  def get_url(page)
    url_for( :controller => :my_controller, :action => :show, :path => page.path )
  end

end

问题是,url_for 引发了这个错误:

The problem is, url_for is raising this error:

undefined local variable or method `_routes'

我想我只是缺少一个包含.有谁知道它应该是什么?

I think I'm just missing an include. Does anyone have an idea what it should be?

**更新***

**UPDATE***

这是堆栈跟踪的一部分:

Here's part of the stack trace:

actionpack (3.0.7) lib/action_dispatch/routing/url_for.rb:131:in `url_for'
actionpack (3.0.7) lib/action_view/helpers/url_helper.rb:99:in `url_for'

所以我认为它一定是一些 ActiveDispatch 依赖,虽然我无法弄清楚

So I think it must be some ActiveDispatch dependency, although I cannot figure out

推荐答案

胜利!

include ActionView::Helpers
include ActionDispatch::Routing
include Rails.application.routes.url_helpers

通过http://apidock.com/rails/ActionController/UrlWriter

这篇关于在 lib 文件夹模块中使用 url_for的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆