LoginSignup
2
1

More than 3 years have passed since last update.

なんかピーンときたので、stimulusを試してみることにした(Railsへの適用)。

Last updated at Posted at 2019-05-15

【控えめで小さなフレームワーク】という響きに惹かれ、stimulusを勉強してみることにした(Vue.jsが難しすぎて投げ出した、という真実からは目を逸しつつ……)。

とりあえず、既存railsに適用できるのか試してみる。

まずはテキトウなrailsアプリを作成

ターミナル(環境確認)
ruby -v
→ruby 2.6.3p62
rails -v
→Rails 5.2.3

で、

ターミナル
rails new test_stimulus2  -d postgresql ※プロジェクト作成
  ↓
cd test_stimulus2 ※作成したところに移動
  ↓
rails g scaffold users cd:string name:string  ※簡単に「ユーザーの登録」を作る
  ↓
rails db:create
rails db:migrate

……プロジェクト名に「2」が付いているのは気にしない方向で(付けていない「test_stimulus」も作っているが、復習も兼ねて再作成中)。

ちなみにはじめから「stimulus」を導入する場合は、
rails new project_name
  ↓↓↓
rails new project_name --webpack=stimulus
とするらしい?(まだ試していない)

作ったモノにstimulusを導入

……https://fuyu.hatenablog.com/entry/2018/11/18/115909を参照しつつ。

gemfileに

gem 'webpacker'

を記述。
ついでに『group :development, :test do』部分には

gem 'pry-rails'
gem 'better_errors'
gem 'binding_of_caller'
gem 'pry-byebug'

も書いておく(検証用に)。
保存したらターミナルで、

ターミナル
bundle install ※gemをインストール
  ↓
rails webpacker:install 
  ↓
rails webpacker:install:stimulus 

これで「app/javascript/packs/application.js」が……
スクリーンショット 2019-05-15 13.42.34.png
出来ている、のかな?

そうしたら「application.js」と同じフォルダ下、「app/javascript/controllers(ここに、stimulus用ファイルを作ってく)」をビューが読み込むよう、

app/views/layouts/application.html.erb
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

    <%# ↓これを追記↓ %>
    <%= javascript_pack_tag 'application' %>
    <%# ↑これを追記↑ %>

とビュー側に追記する。

導入……できた?

導入作業はこれで完了のはずだが、、、自身がないのでとりあえず確認。

Handbookの【Hello, Stimulus】を試してみる。

scaffoldで作成していた一覧に、

app/views/users/index.html.erb
<p id="notice"><%= notice %></p>

<%# ↓これを追記↓ %>
<div data-controller="hello">
  <input data-target="hello.name" type="text">
  <button data-action="click->hello#gree
t">Greet</button>
</div>
 <%# ↑これを追記↑ %>

<h1>Users</h1>

そんでもって、javascript/controllersにhello_controller.jsを……作成しようとしたら、もう出来てたので内容を書き換え(あ、動作確認だけなら自動で作られたやつで足りたのかもしれないけど……まあいいや)。

app/javascript/controllers/hello_controller.js
import { Controller } from "stimulus"

export default class extends Controller {
  static targets = [ "name" ]

  greet() {
    console.log(`Hello, ${this.name}!`)
  }

  get name() {
    return this.nameTarget.value
  }
}

スクリーンショット 2019-05-15 14.06.11.png

おお、ちゃんと適用されてる、されてる!
というか、本当にこれだけで環境を整えられるんだ(結構本気で驚いた)。

とりあえずはここまで、具体的な使い方はこれから探っていく予定。

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