Search code examples
ruby-on-railsgoogle-maps-api-3api-key

How to safely store Google Api keys with rails and use them in scripts?


I'm trying to safely store the Google api key that I'm using in a rails project. I tried storing it in a my secrets.yml file but if I then say in my google script &key=ENV['google_api'], it can't fetch it.

I'm pretty sure this is not the way but after googling the topic, I can't really find a clear answer on this. Anyone who can offer some help?

Thanks, Thomas

UPDATE, here's the code I'm using to fetch the key in my layouts file: Issue, I'm still receiving the error that my api_key is "nil".

  <script>
    var GOOGLE_API_KEY="#{ENV['GOOGLE_API_KEY']}"
  </script>
  <%= javascript_include_tag "//maps.google.com/maps/api/js?v=3.23&key=#{ENV['GOOGLE_API_KEY']}&libraries=geometry,places&language=&hl=&region=&callback=initMap"%>

Solution

  • You will want to put the script call in your application.html.erb file so ruby can parse the ENV['google_api']. Here is an example application file (in HAML):

    !!!
    %html
      %head
        %title Pursuit
        = stylesheet_link_tag 'application', media: 'all'
        = csrf_meta_tags
    
        :javascript
          var GOOGLE_API_KEY="#{ENV['GOOGLE_API_KEY']}"
        = javascript_include_tag 'application'
        = javascript_include_tag "//maps.googleapis.com/maps/api/js?libraries=places&key=#{ENV['GOOGLE_API_KEY']}"
    
      %body
        = render 'layouts/menu'
        .row
          .col.m12.l10.offset-l1
            = yield