rails 4 asset pipeline image subdirectories

2020-05-15 05:08发布

问题:

I know this is probably an easy question but I am stumped here.

The application I am working on houses assets like so:

app
--assets
----fonts
----images
----javascripts

I like to organize assets efficiently to avoid a mess down the road so I am trying to break up images like so:

app
--assets
----fonts
----images
------icons
------views
--------home
--------admin

Ideally I would like to reference images like image.png without having to add the folder path in front of the asset like views/home/image.png which I believe has to be possible although not setup like that out of the box.

回答1:

It's possible if you manually add all paths underneath app/assets/images to the Rails asset paths in your application.rb:

Dir.glob("#{Rails.root}/app/assets/images/**/").each do |path|
  config.assets.paths << path
end


回答2:

In Rails 4+ any changes to asset paths should be made in:

config/initializers/assets.rb

To add all subdirectories in app/assets/images to the path, add the following:

Dir.glob("#{Rails.root}/app/assets/images/**/").each do |path|
  Rails.application.config.assets.paths << path
end

Afterwards, you can verify the asset paths in the rails console with the following:

Rails.application.config.assets.paths.each do |p|
  puts p
end