在rails配置文件和javascript之间共享变量

时间:2015-04-11 13:37:57

标签: ruby-on-rails ruby ruby-on-rails-4

如何在:

之间共享变量
config/initializers/omniauth.rb

app/assets/javascripts/facebook.js.coffee

必须在两个地方设置应用ID似乎疯狂笨重。

OmniAuth.config.logger = Rails.logger

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, 'YOUR-APP-ID-HERE', 'YOUR-APP-SECRET-HERE'
end

和咖啡

jQuery ->
  $('body').prepend('<div id="fb-root"></div>')

  $.ajax
    url: "#{window.location.protocol}//connect.facebook.net/en_US/all.js"
    dataType: 'script'
    cache: true


window.fbAsyncInit = ->
  FB.init(appId: 'YOUR-APP-ID', cookie: true)

  $('#sign_in').click (e) ->
    e.preventDefault()
    FB.login (response) ->
      window.location = '/dedit/auth/facebook/callback' if response.authResponse

  $('#sign_out').click (e) ->
    FB.getLoginStatus (response) ->
      FB.logout() if response.authResponse
    true

1 个答案:

答案 0 :(得分:5)

Rails 4.1

您将在config文件夹中找到secrets.yml文件。添加此功能是为了拥有凭据的公共存储位置。

配置/ secrets.yml

development:
  fb_app_id: something
  fb_app_secret: something

test:
  fb_app_id: something
  fb_app_secret: something

production:
  fb_app_id: <%= ENV["FB_APP_ID"] %>
  fb_app_secret: <%= ENV["FB_APP_SECRET"] %>

要访问 secrets.yml 文件中的各种密钥,您只需执行以下操作:

Rails.application.secrets.fb_app_id
Rails.application.secrets.fb_app_secret

提供您的咖啡脚本 .erb 扩展程序,然后您就可以:

FB.init(appId: '<%= Rails.application.secrets.fb_app_id %>', cookie: true)

您的 omniauth.rb 将如下所示:

OmniAuth.config.logger = Rails.logger

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, Rails.application.secrets.fb_app_id, Rails.application.secrets.fb_app_secret
end