Javascriptにrailsの環境変数を渡す
実現すること
FullcalenderとGoogleカレンダーの連携の際、GoogleカレンダーAPIのキーなどを設定するのにJavascriptを使います。
そこでAPIのキーをgithubなどで公開しないように、環境変数に隠す方法のメモ。
調べてみたら結構簡単でした。
calender.js $(document).ready(function(){ $('#calendar').fullCalendar({ #ここ↓ googleCalendarApiKey: 'APIのキー', eventSources: [ { #ここ↓ googleCalendarId: 'カレンダーのid', (省略) }, { #ここ↓ googleCalendarId: 'カレンダーのid, (省略) } ] }); }); });
必要なgemをインストール
gemfile gem 'gon' gem 'dotenv-rails'
bundle install
.envファイルの作成
青の枠にある.envファイルです。こちらを作成します。
jsファイル内で利用したい、環境変数を.envファイルに記入していきます。
.env GOOGLE_CALENDER_API_KEY='Google側で取得したkey' CALENDER_ID_1='Google側で取得したID' CALENDER_ID_2='Google側で取得したID'
.gitignoreファイルを編集
.gitignoreファイルに.envを記述しないと隠蔽できないので編集します。
.gitignore /.env
application.html.erbの編集
head内に以下を記述します。Javascriptより前に書かないと動かないそうです。
application.html.erb <%= include_gon %>
コントローラーのメソッド内で使用する環境変数を取得
example_controller.rb def example gon.google_calender_API_key = ENV['GOOGLE_CALENDER_API_KEY'] gon.calender_id_1 = ENV['CALENDER_ID_1'] gon.calender_id_2 = ENV['CALENDER_ID_2'] end
ちょっと長くて見にくいので実際はヘルパーメソッドですっきり表示させてます。
example_helper.rb #Googleカレンダー表示に必要な情報取得 def set_google_calender gon.google_calender_API_key = ENV['GOOGLE_CALENDER_API_KEY'] gon.calender_id_1 = ENV['CALENDER_ID_1'] gon.calender_id_2 = ENV['CALENDER_ID_2'] end
example_controller.rb include ExampleHelper def example set_google_calender end
jsファイルに記述
あとはコントローラーで取得した環境変数を書いたら無事完了です!
calender.js >|javascript| $(document).ready(function(){ $('#calendar').fullCalendar({ #ここ↓ googleCalendarApiKey: gon.google_calender_API_key, eventSources: [ { #ここ↓ googleCalendarId: gon.calender_id_1, (省略) }, { #ここ↓ googleCalendarId: gon.calender_id_2, (省略) } ] }); }); });