简体   繁体   中英

Add custom methods to Rails 3.1 asset pipeline?

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

The best way I found was to create a custom helper module in app/helpers:

module AssetsHelper
  def my_custom_helper_method
    # do something  
  end
end

And then to require it like this in application.rb, after your applications configuration (very bottom):

module Sprockets::Helpers::RailsHelper
  require Rails.root.join('app', 'helpers', 'assets_helper.rb')
  include AssetsHelper
end

And you might follow this issue to find a better way: https://github.com/rails/rails/issues/3282

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM