rake assets:precompile:nodigest in Rails 4

前端 未结 6 1438
耶瑟儿~
耶瑟儿~ 2021-01-11 17:03

In Rails 3 there was a rake assets:precompile:nodigest task which was compiling assets and writing them without the digest part in /public/assets directory. In Rails 4 this

6条回答
  •  情话喂你
    2021-01-11 17:37

    As the best answer suggested, I recommend go reading the issue first to fully understand the background story, if you're not in a hurry. I like this idea most, https://github.com/rails/sprockets-rails/issues/49#issuecomment-24837265.

    And below is my personal take, basically I took the code from the answer above. In my case I only have 2 files that I want to be non digested, widget.js and widget.css. So I use sprockets method to find the digested files and then symlink it to public folder.

    # config/environments/production.rb
    config.assets.precompile += %w[v1/widget.js v1/widget.css]
    
    # lib/tasks/assets.rake
    namespace :assets do
      desc 'symlink digested widget-xxx.js and widget-xxx.css to widget.js and widget.css'
      task symlink_widget: :environment do
        next if Rails.env.development? || Rails.env.test?
    
        digested_files = []
        # e.g. /webapps/myapp/public/assets
        assets_path = File.join(Rails.root, 'public', Rails.configuration.assets.prefix)
    
        %w(v1/widget.js v1/widget.css).each do |asset|
          # e.g. 'v1/widget-b61b9eaaa5ef0d92bd537213138eb0c9.js'
          logical_path = Rails.application.assets.find_asset(asset).digest_path
          digested_files << File.join(assets_path, logical_path)
        end
    
        fingerprint_regex = /(-{1}[a-z0-9]{32}*\.{1}){1}/
        digested_files.each do |file|
          next unless file =~ fingerprint_regex
    
          # remove fingerprint & '/assets' from file path
          non_digested = file.gsub(fingerprint_regex, '.')
                             .gsub(Rails.configuration.assets.prefix, '')
    
          puts "Symlinking #{file} to #{non_digested}"
          system "ln -nfs #{file} #{non_digested}"
        end
      end
    end
    

提交回复
热议问题