【Railsサンプルアプリ】RailsのバージョンをVueで表示

サンプルアプリとしてRailsのバージョンをVueで表示してみます。
Rails側は、バージョンを返すWebAPIを作成し、Vue側でWebAPIを呼び出す方式とします。
概要
- Rails側
- Railsアプリ[version]を作成
- データベースの設定
- Controller[version]を作成
- router.rbの設定
- Vue側
- Vueプロジェクト[version]を作成
- Railsバージョン取得APIの追加
詳細
Railsアプリ[version]を作成
versionという名前でRailsアプリを作成します。
$ rails new version -BCMT --skip-coffee -d postgresql create create README.md create Rakefile create .ruby-version create config.ru create .gitignore create Gemfile run git init from “." 〜〜省略〜〜
bundlerで必要なGemをインストールします。
$ cd version/ $ bundle lock --add-platform x64-mingw32 x86-mingw32 Fetching gem metadata from https://rubygems.org/......... Fetching gem metadata from https://rubygems.org/. Resolving dependencies............. ~~ 省略 ~~ $ bundle install Fetching gem metadata from https://rubygems.org/......... Using rake 12.3.2 Using concurrent-ruby 1.1.4 Using i18n 1.2.0 Using minitest 5.11.3 Using thread_safe 0.3.6
データベースの設定
データベース接続の設定をします。
config/database.ymlを編集
変更前
development: <<: *default database: version_development
変更後
development: # <<: *default # database: version_development adapter: postgresql encoding: unicode database: rails_dev pool: 5 username: rails_user password: host: localhost
試しに動作を見てみます。
$ bin/rails s
http://localhost:3000にアクセスし、画面が表示されることを確認します。

Controller[version]を作成
controller作成時に作成されるファイルを減らすため、generators.rbを設定する。
config/initializers/generators.rb編集(存在しないので作成)する
Rails.application.config.generators do |g| g.helper false g.assets false g.skip_routers true g.test_framework false end
controllerを作成する
$ bin/rails g controller version index create app/controllers/version_controller.rb route get 'version/index' invoke erb create app/views/version create app/views/version/index.html.erb
app/controllers/version_controller.rbを編集する。
railsとrubyのバージョンをJSONで返す設定とする。
class VersionController < ApplicationController
def index
version = {'rails' => Rails.version, 'ruby' => RUBY_PLATFORM}
render :json => version
end
end
router.rbの設定
config/router.rbを以下のように編集する。
Rails.application.routes.draw do get "version" => "version#index" # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
ここまでの結果をブラウザで動作確認する。
http://localhost:3000/version

Vueプロジェクトの作成
$ vue init webpack version ? Project name version ? Project description A Vue.js project ? Author vue ? Vue build standalone ? Install vue-router? No ? Use ESLint to lint your code? No ? Set up unit tests No ? Setup e2e tests with Nightwatch? No ? Should we run `npm install` for you after the project has been created? (recommended) yarn vue-cli · Generated "version". # Installing project dependencies ... # ======================== yarn install v1.12.3 info No lockfile found. [1/5] ? Validating package.json... [2/5] ? Resolving packages... warning autoprefixer > browserslist@2.11.3: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools. warning css-loader > cssnano > autoprefixer > browserslist@1.7.7: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools. warning css-loader > cssnano > postcss-merge-rules > browserslist@1.7.7: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools. warning css-loader > cssnano > postcss-merge-rules > caniuse-api > browserslist@1.7.7: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools. warning webpack-bundle-analyzer > bfj-node4@5.3.1: Switch to the `bfj` package for fixes and new features! [3/5] ? Fetching packages... [4/5] ? Linking dependencies... [5/5] ? Building fresh packages... success Saved lockfile. ✨ Done in 34.98s. # Project initialization finished! # ======================== To get started: cd version npm run dev Documentation can be found at https://vuejs-templates.github.io/webpack
WebAPIの取得にaxiosを使用する。
version/index.htmlに外部スクリプト呼び出しのため<script>タグを追加する
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>version</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
そもそもHelloWorld.vueのどこに何が書かれているかは、以下が参考になった。
「Vue.js を vue-cli を使ってシンプルにはじめてみる」
https://qiita.com/567000/items/dde495d6a8ad1c25fa43
version/src/components/HelloWorld.vueに画面ロード時にWebAPIを呼び出す処理を追加する。
dataにresults変数を追加し、<template>内に表示する。
また、mounted()にWebAPIのGET処理を追加する。
HelloWorld.vue
<template>
<div class="hello">
<p>Rails : {{ results.rails }}</p>
<p>Ruby : {{ results.ruby }}</p>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App',
results: []
}
},
mounted() {
axios.get("http://localhost:3000/version")
.then(response => {this.results = response.data})
}
}
</script>
ここまでで動作確認してみます。
$ npm run dev
http://localhost:8080にブラウザでアクセス
ChromeでF12で確認するとCORSのメッセージが出ています。Origin(Schema/Host/Portの組み合わせ)がport3000と8080で異なるため、クロスオリジン通信となり、CORSに引っかかっています。

CORSへの対応は、別の記事で書きます。
次の記事はこちら【Railsサンプルアプリ】Rails – VueアプリのCORS対応
ソースはこちら(GitHub)
「【Railsサンプルアプリ】RailsのバージョンをVueで表示」への1件のフィードバック