環境作り
まだまだ初歩的なところも染みついてないので、環境構築から繰り返す。
Dockerを利用するので、まずはCentos6のコンテナを作る。
sudo docker run -it -p 9292 –name test centos:centos6 /bin/bash
9292はあとから使うので開けときます。お肉が食べたい訳ではありません。
お肉食べたいけどね。
こいつを叩きまくるとコンテナのシェルになっているので
さて、先立つものを用意しますかね。
# yum update -y
# yum install -y ruby-devel ruby gcc rdoc git tar sudo vim sqlite-devel openssl-devel
# vi ~/.gemrc
install: --no-rdoc --no-ri
update: --no-rdoc --no-ri
vimrc何かは自分のを入れたりしてね。
activesuportがruby 1.9.3以降でないと入らないのでそもそもrubyのバージョンなんかは先に上げといた方が楽です。
て事で、rbenvをインストール
# git clone https://github.com/sstephenson/rbenv.git ~/.rbenv
編集しちゃいます。
# vi ~/.bash_profile
export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"
有効に。
# exec $SHELL -l
上手く入ったか確認。
# rbenv -v
rbenv 0.4.0-129-g7e0e85b
続いてruby-build
# git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
バージョン確認。
# rbenv install --list
~~ 略 ~~
最新の安定版を。
# rbenv install -v 2.1.5
バージョン指定して有効に。
# rbenv global 2.1.5
確認。
# ruby -v
ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-linux]
終了。
# rbenv rehash
bundlerをインストールして、この辺でコミットするのもいいかも?
# gem install bundler
Ctrl + p q でコンテナを抜けて、コミット。
$ sudo docker commit コンテナ リポジトリ
Bundle exec
今回、Dockerで独立した環境を作っているのだから、わざわざBundle execしなくても良いような気がしますが、雰囲気も大事だと思うのでBundle execしてます。
が、やっているうちにあああああ、Bundle exec 省略したぁぁぁぁぁぁぁぁい。
って思えてきたので、やはり省略する手順があってしかるべきなのだなと感じました。
ていうか、このテストの為に作ったコンテナだしそのままでもいいじゃね??
と言う風にループするので、バカな自問自答はこのくらいにして先に進もう。
結局どうしたかというと、適当なディレクトリを作ってbundle init しましたとさ。
このコンテナを使いまわしたいのだよね。
rackな環境作り
Gemfileには
source "https://rubygems.org"
gem 'sinatra'
gem 'activerecord'
gem 'sinatra-activerecord'
gem 'sqlite3'
# bundle install --path=vendor/bundle
今回はrackを使いたいので、config.ruを先に作る。
vi config.ru
require './app.rb'
run Sinatra::Application
app.tb
get '/' do
'Hello'
end
起動してみよう。今回は前のような-o とか-e のオプションはいらない。
# bundle exec rackup config.ru
アクセスはちゃんとホストから見て開いているポートなのでちょっと注意ね。
curl http://localhost:Dockerで繋いでるポート番号
なので、
$ curl http://localhost:49153
Hello
これで準備OKですね。
migrate
Rakefileでactiverecordと、app.rbに接続部を書くのでrequire。
# cat Rakefile
require 'sinatra/activerecord/rake'
require './app'
タスク確認
# bundle exec rake -T
rake db:create # Creates the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:create:all t...
rake db:create_migration # Create a migration (parameters: NAME, VERSION)
rake db:drop # Drops the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to dr...
rake db:fixtures:load # Load fixtures into the current environment's database
rake db:migrate # Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)
rake db:migrate:status # Display status of migrations
rake db:rollback # Rolls the schema back to the previous version (specify steps w/ STEP=n)
rake db:schema:cache:clear # Clear a db/schema_cache.dump file
rake db:schema:cache:dump # Create a db/schema_cache.dump file
rake db:schema:dump # Create a db/schema.rb file that is portable against any DB supported by AR
rake db:schema:load # Load a schema.rb file into the database
rake db:seed # Load the seed data from db/seeds.rb
rake db:setup # Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the datab...
rake db:structure:dump # Dump the database structure to db/structure.sql
rake db:version # Retrieves the current schema version number
これでrake db:create_migrationができるようになった。
という事だろう。
では、実際にやってみると。
[root@def85521b282 db]# bundle exec rake db:create_migration NAME=create_users
db/migrate/20141205155116_create_users.rb
USAGE
https://github.com/janko-m/sinatra-activerecord/blob/master/README.md
sinatra-activerecord/README.md at master ・ janko-m/sinatra-activerecord:
スクリプトはこんな感じにしてみました。この場合は、:usersというのがテーブル名となります。
db/migrate/20141205155116_create_users.rb
# cat db/migrate/20141205155116_create_users.rb
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.integer :number, :default => 0
t.string :name
t.string :address
t.timestamps
end
end
end
app.rbに接続部分を追記します。
app.rb
require 'sinatra'
require 'active_record'
ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: 'development.sqlite3'
)
get '/' do
'Hello'
end
ではおまちかねのマイグレーションに!
の前にマイグレーションとはなんぞや?と自分に聞いてみると答えられない。
何となくマイグラデュエーションとかマイレボリューションと間違えそうになってしまうが
そもそも、my grationじゃなくてmigration だ。
1つの単語だ。そこんとこよろしく。
意味を調べると、データなどを別の環境に移転したり、新しい環境に切り替えたりする
という事らしいので奇しくも、My Revolutionだったりmy graduationと意味的に近いものだったらしい。
rake db:migrationで何ができるのかとなると、テーブルを作成したり変更を加えたりできる機能のようだ。
bundle exec rake db:migrate
[root@def85521b282 db]# bundle exec rake db:migrate
== 20141205155116 CreateUsers: migrating ======================================
-- create_table(:users)
-> 0.0028s
== 20141205155116 CreateUsers: migrated (0.0029s) =============================
成功しているので、記述された通りにテーブルが作成されたはずです。
心配なので確認してみます。
[root@def85521b282 db]# bundle exec rake db:migrate:status
database: development.sqlite3
Status Migration ID Migration Name
--------------------------------------------------
up 20141205155116 Create users
接続してテーブルを確認してみます。
[root@def85521b282 db]# sqlite3 development.sqlite3
SQLite version 3.6.20
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .database
seq name file
--- --------------- ----------------------------------------------------------
0 main /root/db/development.sqlite3
sqlite> .schema
CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL);
CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "number" integer DEFAULT 0, "name" varchar(255), "address" varchar(255), "created_at" datetime, "updated_at" datetime);
CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version");
出来ていました!やったね。
よく見るとidという主キーを持ったのがありますが、記述していなくても暗黙で生成されるものらしいです。
これで準備はだいたい出来た訳であとはアイデアとコーディングスキルがあれば何でもできるという事。そこが大事なんだがね。
今回はmigrateが目的だったのでこれにて終了ですじゃ~。
参考サイト
SinatraからActiveRecord 3を使う(1) マイグレーション – アインシュタインの電話番号:
sinatra-activerecord/README.md at master · janko-m/sinatra-activerecord:
SinatraでActiveRecord使う – 飲んだり寝たり: