Skip to content

Instantly share code, notes, and snippets.

@ramonrails
Created November 15, 2016 12:06
Show Gist options
  • Save ramonrails/1b3aec14b65c8c5976b0a983455a6c0c to your computer and use it in GitHub Desktop.
Save ramonrails/1b3aec14b65c8c5976b0a983455a6c0c to your computer and use it in GitHub Desktop.
rails: dynamically pickup controller-named-assets for pre-compilation
# config/initializers/assets.rb
javascripts = [...]
stylesheets = [...]
images = [...]
fonts = [...]
# NOTE: dynamically include for precompile: controller specific .coffee, .js and .scss, .css
#
# step 1: collect controller basenames
controllers = Dir.glob(File.join(Rails.root, 'app', 'controllers', '*.rb'))
.collect { |e| File.basename(e, '.rb').split('_').first }
controllers -= ['application'] # exclude the main file
#
# step 2: collect /app/assets/javascripts/*.coffee,js (that match controller names)
javascripts += Dir.glob(File.join(Rails.root, 'app', 'assets', 'javascripts', "{#{controllers.join(',')}}.{coffee,js}"))
.collect { |e| File.basename(e) }
#
# step 3: collect /app/assets/stylesheets/*.scss,css (that match controller names)
stylesheets += Dir.glob(File.join(Rails.root, 'app', 'assets', 'stylesheets', "{#{controllers.join(',')}}.{scss,css}"))
.collect { |e| File.basename(e) }
Rails.application.config.assets.precompile += (javascripts + stylesheets + images + fonts)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment