Skip to content

Instantly share code, notes, and snippets.

@mfurtak
Created August 4, 2012 23:26
Show Gist options
  • Save mfurtak/3260563 to your computer and use it in GitHub Desktop.
Save mfurtak/3260563 to your computer and use it in GitHub Desktop.
Fixing use of I18n.t during asset precompilation on Heroku
# Rake task overriding, with original task calling. Found here:
#
# http://metaskills.net/2010/05/26/the-alias_method_chain-of-rake-override-rake-task/
Rake::TaskManager.class_eval do
def alias_task(fq_name)
new_name = "#{fq_name}:original"
@tasks[new_name] = @tasks.delete(fq_name)
end
end
def alias_task(fq_name)
Rake.application.alias_task(fq_name)
end
def override_task(*args, &block)
name, params, deps = Rake.application.resolve_args(args.dup)
fq_name = Rake.application.instance_variable_get(:@scope).dup.push(name).join(':')
alias_task(fq_name)
Rake::Task.define_task(*args, &block)
end
# Heroku requires that config.assets.initialize_on_precompile be set to false, which
# means you can't use I18n.t translations in your precompiled assets. Overriding the
# assets:precompile task to get the config/locales/*.yml files back on the I18n load
# path fixes this.
namespace :assets do
desc "Replay application events to reconstruct application state"
override_task :precompile do
puts "*** Running overloaded assets:precompile! ***"
I18n.load_path += Dir[Rails.root.join('config', 'locales', '*.{rb,yml}').to_s]
Rake::Task["assets:precompile:original"].execute
end
end
@13k
Copy link

13k commented Sep 24, 2012

Do you know if this works for non-en locales? I added I18n.default_locale = :"pt-BR" just below the load_path line and it keeps trying to use the en locale (and since I don't have the strings in en, it outputs the missing translation message).

On another note, do you really need to alias the task? I first thought about adding a task dependency to the assets:precompile task in which it sets the load_path:

task :configure_i18n do
  # I18n.load_path ...
end

Rake::Task["assets:precompile"].enhance [:configure_i18n]

If I puts inside the :configure_i18n task and call rake assets:precompile it outputs so it's definitely being called. Since your (that blog's) method is just wrapping the original task, it seems to be the same thing. enhanceing is a default supported way to do it for Rake, though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment