4
4

More than 5 years have passed since last update.

HerokuでSinatraアプリを作るときに調べたこと困ったことまとめ

Posted at

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')
4
4
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
4
4