[英]How to access params hash in lib directory rails 6
在我的 rails 应用程序中,我使用 Kramdown 来解析 Markdown。 我想扩展 HTML 转换器中convert_a
方法的功能。 其中一部分涉及访问数据库,但它依赖于 URL 中的参数。 因为我没有直接调用我要覆盖的方法,所以我不能简单地将该方法传递给params
哈希值。 有没有办法访问这个散列,或者甚至只是在lib
目录中的模块中获取当前 URL?
为了提供更多上下文,方法调用位于此处的辅助方法中:
# in app/helpers/myhelper.rb
def to_html(text)
Kramdown::Document.new(text, parse_block_html: true).to_custom_html
end
这是我覆盖convert_a
的文件:
# in lib/custom_html.rb
class CustomHtml < Kramdown::Converter::Html
def convert_a(el, indent)
# use params[:foo] to make query
format_as_span_html(el.type, el.attr, inner(el, indent))
end
end
编辑:
提供有关调用覆盖方法的位置的更多上下文。 我对 Kramdown 代码库不是很熟悉,但是似乎当to_custom_html
被调用时,下面的代码是在Kramdown.rb
运行的:
output, warnings = Converter.const_get(name).convert(@root, @options)
随后在内部 kramdown 元素上调用convert_#{el.type}
。
您可以在Kramdown::Document#new
传递其他选项,因此只需执行Kramdown::Document.new(text, my_params: params)
。 然后您可以使用转换器的#options
方法来访问您的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.