Setting Environment Variables in Rails 3 (Devise + Omniauth)

后端 未结 3 1543
鱼传尺愫
鱼传尺愫 2020-11-29 16:52

I\'ve been trying to figure out how Ryan Bates, in his Facebook Authentication screencast, is setting the following \"FACEBOOK_APP_ID\" and \"FACEBOOK_SECRET\" environment

相关标签:
3条回答
  • 2020-11-29 17:00

    There are several options:

    • Set the environment variables from the command line:

      export FACEBOOK_APP_ID=your_app_id
      export FACEBOOK_SECRET=your_secret
      

      You can put the above lines in your ~/.bashrc

    • Set the environment variables when running rails s:

      FACEBOOK_APP_ID=your_app_id FACEBOOK_SECRET=your_secret rails s
      
    • Create a .env file with:

      FACEBOOK_APP_ID=your_app_id
      FACEBOOK_SECRET=your_secret
      

      and use either Foreman (starting your app with foreman start) or the dotenv gem.

    0 讨论(0)
  • 2020-11-29 17:10

    You could take a look at the comments:

    You can either set environment variables directly on the shell where you are starting your server:

    FACEBOOK_APP_ID=12345 FACEBOOK_SECRET=abcdef rails server
    

    Or (rather hacky), you could set them in your config/environments/development.rb:

    ENV['FACEBOOK_APP_ID'] = "12345";
    ENV['FACEBOOK_SECRET'] = "abcdef";
    

    An alternative way

    However I would do neither. I would create a config file (say config/facebook.yml) which holds the corresponding values for every environment. And then load this as a constant in an initializer:

    config/facebook.yml

    development:
      app_id: 12345
      secret: abcdef
    
    test:
      app_id: 12345
      secret: abcdef
    
    production:
      app_id: 23456
      secret: bcdefg
    

    config/initializers/facebook.rb

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

    Then replace ENV['FACEBOOK_APP_ID'] in your code by FACEBOOK_CONFIG['app_id'] and ENV['FACEBOOK_SECRET'] by FACEBOOK_CONFIG['secret'].

    0 讨论(0)
  • 2020-11-29 17:12

    Here's another idea. Define the keys and values in provider.yml file, as suggested above. Then put this in your environment.rb (before the call to Application.initialize!):

    YAML.load_file("#{::Rails.root}/config/provider.yml")[::Rails.env].each {|k,v| ENV[k] = v }
    

    Then these environment variables can be referenced in the omniauth initializer without any ordering dependency among intializers.

    0 讨论(0)
提交回复
热议问题