Rails precompile constant uninitialized

I wanted to preload the configuration (from .yml files). In one of my initializer files (config / initializers / facebook.rb) I have the following line of code:

FACEBOOK_CONFIG = YAML.load_file("#{Rails.root}/config/facebook.yml")[Rails.env]

So, it works like a charm in "DEVELOPMENT" mode. When I switch to production mode, he keeps telling me that FACEBOOK_CONFIG is an uninitialized constant for my file " facebook.js.coffee.erb" located in assets / javascript (if that matters) if I want o "rake assets: precompile". I tried doing random things like: RAILS_ENV=production bundle exec rake assets:precompileor

rake assets: precompile: all

but no luck

I tried to assign the variable " initialize_on_precompile = true" to my production environment (although by default it should be true), just in case.

Why it does not work in production mode (but I want to emphasize that it works (!) In the development environment).

Can anyone help with this?

+5
source share
2 answers

I ran into the same problem. This is because your javascript (coffescript) file refers to a constant defined in the initializer. Since it is precompiled before the initializer, the application displays an error message.

This is a simple solution that I have found. You place this code at the bottom of the application.rb file in config:

module AssetsInitializers
  class Railtie < Rails::Railtie
    initializer "assets_initializers.initialize_rails",
                :group => :assets do |app|
      require "#{Rails.root}/config/initializers/facebook.rb" 
    end
  end
end

. .

, .

+4
module Rails

  class << self
    def facebook_config
      @@facebook_config ||= nil
    end

    def facebook_config=(facebook_config)
      @@facebook_config = facebook_config
    end
  end
end

Rails.facebook_config = YAML.load_file("#{Rails.root}/config/facebook.yml")[Rails.env]

# And you can use it like this in anywhere:
puts Rails.facebook_config
0

All Articles