LoginSignup
25
26

More than 5 years have passed since last update.

sinatraのデーモン起動とpadrino移行

Last updated at Posted at 2013-04-26

sinatraでアプリを作ったけど、デーモン起動と他のマシンからのアクセスがしたかったので結局padrinoに移行した。

sinatraで動かす

最小限のサンプルアプリ書いてそれを実行してみた。
gemがインストールされていなければgem install sinatra slimが必要。

コードを書く

app.rb
require 'sinatra'
require 'slim'

get '/index' do
  slim :index
end

def greet
  "Hello World!"
end

__END__

@@index
h1 = greet

起動

$ ruby app.rb -p 3000

ポート指定がない場合は4567ポートで起動される。
http://localhost:3000/indexにアクセスするとHello World!と表示される。

sinatraをデーモンで起動する

unicornを使ってデーモン起動する。
基本的には先ほど作ったapp.rbを改造する。
gemがインストールされていなければgem install unicornが必要。

コードを書く

app.rb
require 'sinatra'
require 'slim'

class App < Sinatra::Base
  get '/index' do
    slim :index
  end

  def greet
    "Hello World!"
  end
end

App.run!
views/index.slim
h1 - greet
unicorn.conf
worker_processes 2
listen '/tmp/unicorn.sock'
stderr_path File.expand_path('unicorn.log', File.dirname(__FILE__))
stdout_path File.expand_path('unicorn.log', File.dirname(__FILE__))
preload_app true

tmpフォルダを作成しておく

起動

$ unicorn -c unicorn.conf -D

padrinoで動かす

gemがインストールされていなければgem install padrinoが必要。
padrino generateとかで適当に構成が作られるのであとは上で作ったファイルを配置して、ちょこっと修正するだけ。

コード

以下を実行した。

$ padrino g project sample -e slim
$ padrino g controller sample get:index

以下のファイルを変更した

app/views/sample/index.slim
h1 = greet
app/controllers/sample.rb
Sample::App.controllers :sample do
  get :index, :map => '/' do
    slim :"sample/index"
  end
end
app/helpers/sample_helper.rb
Sample::App.helpers do
  def greet
    "Hello World!"
  end
end

起動

$ padrino start -p 3000 -d

おわりに

http://localhost:3000/indexにアクセスするとHello World!と表示される。
別のマシンからhttp://(padrinoで起動したマシンのIPアドレス):3000にアクセスしても見れた。
小さいアプリでもサクット作って動かしてみる程度ならsinatraでもいいが、ある程度の期間使うならpadrinoを使ったほうがいいと感じた。

~ただの宣伝~

  • 全国のSeleniumer必読
  • Seleniumerといっていますが、Selenium, SauceLabs, Travis, Jenkinsに関するノウハウ書いているのでよかったら参考にしてみてください
25
26
2

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
25
26