LoginSignup
6
8

More than 3 years have passed since last update.

【Rails】Rails側で定義した変数をJavaScriptに簡単に渡せるgem 「gon」を使ってみた

Posted at

はじめに

Railsアプリケーションを作成中、JavaScriptにRails側で定義した変数を渡したくなり、調べたところgonというかなり使い勝手のいいgemがあったので導入してみました。

この記事が役に立つ方

  • Rails側で定義した変数をJavaScript側でも使いたい方

この記事のメリット

  • gonを使ってRailsで定義した変数をJavascriptに渡せるようになる

環境

  • macOS Catalina 10.15.1
  • zsh: 5.7.1
  • Ruby: 2.6.5
  • Rails: 5.2.3
  • Docker: 19.03.5
  • docker-compose: 1.24.1
  • gon: 6.3.2

gemgonとは?

シンプルにRailsアプリ内でJavaScriptに変数を渡すことが出来るgemです。
RSpecにも変数を渡せたりと、便利。

スクリーンショット 2019-12-01 22.05.52.png
GitHub - gazay/gon: Your Rails variables in your JS

If you need to send some data to your js files and you don't want to do this with long way through views and parsing - use this force!

(ざっくり)JavaScriptに何かデータを送る必要があるなら、面倒くさいビューとかパースとかやめてこれを使っちゃいなよ!
と紹介されています。

インストール

Gemfile
gem 'gon'

bundle install

使用方法

Usage example · gazay/gon Wiki · GitHub

1. Viewで読み込み

app/views/layouts/application.html.erb
<head>
  <title>some title</title>
  <%= include_gon %>
  <!-- include your action js code -->

titleタグの下で、javascript_include_tagよりは上。

※公式Wikiであった、以下方法ではうまくいきませんでした。

app/views/layouts/application.html.erb
<head>
  <title>some title</title>
  <%= Gon::Base.render_data %> 
  <!-- include your action js code -->

2. Controllerで使っている変数をgonにセット。

any_controller.rb
@your_int = 123
@your_array = [1,2]
@your_hash = {'a' => 1, 'b' => 2}

# 上記の変数をJavaScriptで呼び出したいなら
# 以下のように頭に`gon`をつけて変数定義する
gon.your_int = @your_int
gon.your_array = @your_array
gon.your_hash = @your_hash

# `gon`をつけた後に別の変数定義に活用することも可能。
gon.your_other_int = 345 + gon.your_int

# `gon`をつけたもの同士で配列に追加も可能。
gon.your_array << gon.your_int
gon.your_array # > [1, 2, 123]

# `all_variables`で`gon`をつけた全ての変数がハッシュで取り出せる
gon.all_variables # > {:your_int => 123, :your_other_int => 468, :your_array => [1, 2, 123], :your_hash => {'a' => 1, 'b' => 2}}

# `clear`で全変数をクリアできる
gon.clear # gon.all_variables now is {}

gonをつけるだけでいいのでシンプルですね。


3. JavaScriptで呼び出し

any.js
alert(gon.your_int)
alert(gon.your_other_int)
alert(gon.your_array)
alert(gon.your_hash)

先程コントローラー側で定義したものがそのまま使えます。
aleatはテキトーです。

当然ですが、例えばcurrent_userを渡していた場合は、

current_user.js
alert(gon.current_user.name)
alert(gon.current_user.email)
alert(gon.current_user.id)

のようにすると名前やメールアドレスなど、欲しいキーを指定すれば値が取り出せます。

非常に分かりやすくて便利です。

おわりに

最後まで読んで頂きありがとうございました:bow_tone1:

他にもinputタグ経由で変数を渡したり、JSONを使ったりして変数を渡している記事を見つけましたが、gonの方がシンプルに変数を渡せるので楽ですね:relaxed:

参考にさせて頂いたサイト(いつもありがとうございます)

6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8