Sinatraのプロジェクト構成
一段落した時点での構成は以下のようになった.
- webapp-dir
- .env // foremanを用いたデバッグ時の環境変数を宣言したファイル
- Gemfile
- Procfile
- Rakefile
- app // 自作のスクリプトやスタイルシートはここ、gulp経由でコンパイルしてまとめる
- script
- app.coffee
- stylesheet
- app.less
- app.rb // コントローラー
- bower.json
- bower_components
- config.ru
- config.sh // Herokuの環境変数設定用のスクリプト
- gulpfile.coffee
- models
- node_modules
- package.json
- public
- views
aの構成というよりはWebプロジェクトの構成という気がする.
これでいいかどうか確信があるわけではない.
参考
セッション
app.rb
に以下を書き足す
app.rb
enable :sessions
使用方法
session[:request_token] = request_token
Sinatraの変数スコープ
Sinatraはリクエストごとにインスタンスを立ち上げるので、あるメソッドでインスタンス変数を初期化しても他メソッドではNil
になるといった場合がある.
そのためhelpers
ブロック内でインスタンス変数を持つようにする.
いい例
get '/' do
client.request1
end
get '/request' do
client.request2 => undefined method `request' for nil:NilClass
end
helpers do
def client
@client ||= Client.new
end
end
悪い例
get '/' do
@client = Client.new
@client.request1
end
get '/request' do
@client.request2 => undefined method 'request' for nil:NilClass
end
参考
URLにおけるスキーム、ホストの補完
url(/app.js) => 'http://localhost:5000/app.js'
サーバ設定の自動更新
sinatra-contrib
というgemを入れてapp.rb
に以下を書き足す.
app.rb
configure :development do
register Sinatra::Reloader
end
参考
ローカル環境
foreman
heroku上での実行環境を再現するのにforeman
というgemを使う
Gemfile
group :development do
gem 'foreman'
end
foremanは.env
というファイルの内容を環境変数として読み込んでくれる.
.env
ENV_VARIABLE="variable"
Postgresql周り
HerokuでPostgresqlのアドオンを利用したのでローカルでの環境も整える.
Homebrewでインストール.
brew install postgresql
postgresqlサーバを起動
postgres -D /usr/local/var/postgres
postgresqlサーバへのアクセス
ActiveRecord::Base.establish_connection(ENV['DATABASE_URL'] || 'postgres://localhost/user')