5

How do I share variable between:

config/initializers/omniauth.rb

and

app/assets/javascripts/facebook.js.coffee

?

having to set app id in two places seems crazy clunky.

OmniAuth.config.logger = Rails.logger

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

and coffee

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 Answer 1

6

Rails 4.1:

You will find a secrets.yml file in config folder. This feature was added in order to have a common storage location for the credentials.

config/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"] %>

To access the various keys in the secrets.yml file you need to simply do:

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

Give your coffee script .erb extension, then you will be able to do:

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

Your omniauth.rb will look like this:

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
Sign up to request clarification or add additional context in comments.

6 Comments

@salivan, did you change your coffeescript extension? something like abc.coffee.erb ?
ofcourse, facebook.js.coffee.erb is this correct? and I also restarted server
I changed few things around and it started to work. Probably the cache was acting up.
weird thing, I just checked if ruby was executing, I put Time.now in place of variable and it worked. Then I put back Rails.application... and it worked :)
The important thing is it worked. And now you are following the Railsway to use credentials. :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.