Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you tell Rails / the asset pipeline that a js.erb depends on a YAML file?

I have a js.erb file that loads YAML from a config file. The problem is that Rails / the asset pipeline will cache the results and never invalidate that cache, even when I change the YAML file contents. I can restart the rails server and even reboot the machine to no avail. The only workaround I've found so far is doing a "rake assets:clean".

I would like to find a way to tell the asset pipeline that when the YAML file changes, it needs to re-compute my js.erb. Or, alternatively, tell it it can only cache the js.erb for the lifetime of the rails server / ensure somehow that re-generation occurs every time the rails server comes up or is restarted.

Any suggestions would be greatly appreciated.

like image 319
user2337118 Avatar asked Sep 15 '25 10:09

user2337118


1 Answers

Add this into a file under config/initializers and it will tell the asset pipeline to re-compute the js.erb file that loads the YAML data whenever one of the backing YAML files changes:

class ConstantsPreprocessor < Sprockets::Processor
  CONSTANTS_ASSET = "support/constants"

  def evaluate(context, locals)
    if (context.logical_path == CONSTANTS_ASSET)
      Constants.load_path.each do |dir|
        dir.each do |yml|
          next unless yml.end_with?".yml"
          context.depend_on("#{dir.path}/#{yml}")
        end
      end
    end

    data
  end
end

Rails.application.assets.register_preprocessor(
    'application/javascript',
    ConstantsPreprocessor)
like image 142
user2337118 Avatar answered Sep 16 '25 23:09

user2337118