向 Rails 3.1 资产管道添加自定义方法?
如何将自定义方法添加到我的资产中,例如 css 文件,就像 Rails 使用“asset_path”助手所做的那样?
有了 Rail 自己的助手,我可以这样写:
# some.css.erb:
<%= asset_path 'a_image.png' %>
# How can I write this:
<%= my_custom_method 'a_image.png' %>
我尝试了很多方法,但找不到合适的方法。你认识一个吗?
谢谢
How can I add my custom methods to my assets such as css files like Rails did with 'asset_path' helper?
With Rail's own helper, I can write this:
# some.css.erb:
<%= asset_path 'a_image.png' %>
# How can I write this:
<%= my_custom_method 'a_image.png' %>
I've tried many ways but couldn't found a decent way to this. Do you know one?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我发现的最好方法是在 app/helpers 中创建一个自定义帮助器模块:
然后在应用程序配置之后(最底部)在 application.rb 中像这样要求它:
并且您可以按照此问题找到更好的方法: https://github.com/rails/rails/issues/3282
The best way I found was to create a custom helper module in app/helpers:
And then to require it like this in application.rb, after your applications configuration (very bottom):
And you might follow this issue to find a better way: https://github.com/rails/rails/issues/3282
普通的辅助方法在资产视图中不可用。要添加您自己的方法,您需要扩展 Sprockets 帮助程序模块。 查看代码内置的助手来看看你可以如何做到这一点。
简而言之,您可以在 lib 中添加一个与此结构相同的文件,并添加您自己的方法。不要忘记将新库包含在应用程序初始值设定项中。
Normal helper methods are not available in asset views. To add you own methods you'll need to extend the Sprockets helper module. Have a look at the code of the built-in helpers to see how you might do this.
In a nutshell you can add a file in lib with the same structure as this and add you own methods. Don't forget to include the new library in you application initializer.