Last active
May 11, 2020 15:11
-
-
Save dylanjha/11233766 to your computer and use it in GitHub Desktop.
Adds Sprockets Directive `depend_on_config`. I'm using this to load .yml locale translations on the server into the client in json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=begin | |
Useage: | |
#assets/locales/en.js.erb | |
```js | |
//= depend_on_config 'locales/es.yml' | |
``` | |
=end | |
class Sprockets::DirectiveProcessor | |
def process_depend_on_config_directive(file) | |
path = File.expand_path(file, "#{Rails.root}/config") | |
context.depend_on(path) | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module JsLocaleHelper | |
def self.output_locale(locale) | |
locale_str = locale.to_s | |
file = Rails.root.join("config/locales/", "#{locale_str}.yml") | |
YAML::load(File.open file)[locale_str].to_json.html_safe | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//= depend_on_config 'locales/es.yml' | |
I18n.translations = I18n.translations || {}; | |
I18n.translations.en = "<%= JsLocaleHelper.output_locale(:en) %>" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
en: | |
hello: Hello World |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Which version of sprockets are you using? This seems to blow up on sprockets 3.4.
undefined local variable or method
context' for #Sprockets::DirectiveProcessor:0x007fe27be37280`