Chris Hough
Chris Hough

Reputation: 3558

rails 4 asset pipeline image subdirectories

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.

Upvotes: 15

Views: 7555

Answers (2)

Eribos
Eribos

Reputation: 271

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

Upvotes: 25

Marcelo De Polli
Marcelo De Polli

Reputation: 29291

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

Upvotes: 32

Related Questions