41
45

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby On Rails Gemまとめ -gon-

Last updated at Posted at 2014-06-17

##gonとは
「gon」はRailsで定義した変数をJavascript内で利用できるようにする。(コントローラからデータの受け渡しが可能になる。)

##インストール・設定
Gemfileに以下を追加。

gem "gon"

ターミナルで$ bundle installを実行。

bundle install後、ヘッダー(app/views/layouts/application.html.erb)に以下の1行を追加。

application.html.erb
...
...
<title>TITLE</title>
<%= include_gon %> ←追加!!
<%= stylesheet_link_tag  "application", media: "all" %>
<%= javascript_include_tag  "application" %>
...
...

##使い方

コントローラ内で「gon.*****」と設定します。

app/controllers/users_controller.rb
class UsersController < ApplicationController
  def index
    gon.user_name = "user_name"
    gon.user_age = 24
    gon.user_favorite_food = ["curry", "sandwich", "steak"]

	#すべての変数を参照
	gon.all_variables  # => {"user_name", 24, ["curry", "sandwich", "steak"]} 

	#クリア
	gon.clear  # => {}

  end
end

Javascriptファイルでは、「gon.*****」でアクセスできます。

app/assets/javascripts/users.js.coffee
alert(gon.user_name)  // => user_name
alert(gon.user_age)  // => 24
alert(gon.user_favorite_food)  // => ["curry", "sandwich", "steak"]
41
45
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
41
45

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?