LodgeをHerokuボタンでデプロイする(PostgreSQL編)


という内容で書こうと思ったところ・・・既に投稿されている方がおられました。
とても参考になりました。ありがとうございます。
私はデータベースにPostgreSQLを使ってみたいと思います。

2014/11/13 追記
画像をS3に保存するようにしました。

**対象**

Lodge v0.10.1

**サンプル**

https://github.com/usutani/lodge_heroku_button/tree/heroku_button

[![Deploy](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy?template=https://github.com/usutani/lodge_heroku_button/tree/heroku_button)

**参照**

- [Lodgeをherokuで動かす(ついでにheroku button)](http://qiita.com/hoshino/items/e058339f1399baab87b0)
- [Rails+Carrierwave+fog+Heroku+S3でハマったメモ](http://qiita.com/kimihito_/items/3ff9c0c4407447ee3ab3)

# 変更箇所

.gitignore
Gemfile
Gemfile.lock
README.md
app.json
config/environments/production.rb

config/initializers/carrierwave.rb 
app/uploaders/image_uploader.rb

## .gitignore

下記のファイルを削除します（版管理の対象にします）。

- Gemfile.lock

```diff
diff --git a/.gitignore b/.gitignore
index fd5054d..83f9f29 100644
--- a/.gitignore
+++ b/.gitignore
@@ -25,7 +25,6 @@
 
 /config/database.yml
 
-/Gemfile.lock
 /vendor/bundle
 lodge_development
 lodge_test
```

## Gemfile

production 環境で、下記の gem を使用します。

- pg
- rails_12factor

```diff
diff --git a/Gemfile b/Gemfile
index 8d66364..e1557a9 100644
--- a/Gemfile
+++ b/Gemfile
@@ -92,30 +92,10 @@ group :test do
   gem 'launchy'
 end
 
-# Include database gems for the adapters found in the database
-# configuration file
-require 'erb'
-require 'yaml'
-database_file = File.join(File.dirname(__FILE__), "config/database.yml")
-if File.exist?(database_file)
-  database_config = YAML::load(ERB.new(IO.read(database_file)).result)
-  adapters = database_config.values.map {|c| c['adapter']}.compact.uniq
-  if adapters.any?
-    adapters.each do |adapter|
-      case adapter
-      when 'mysql2'
-        gem "mysql2", '~> 0.3'
-      when /postgresql/
-        gem "pg", '~> 0.17'
-      when /sqlite3/
-        gem "sqlite3", '~> 1.3'
-      else
-        warn("Unknown database adapter `#{adapter}` found in config/database.yml")
-      end
-    end
-  else
-    warn("No adapter found in config/database.yml, please configure it first")
-  end
-else
-  warn("Please configure your config/database.yml first")
+group :development do
+  gem 'sqlite3'
+end
+group :production do
+  gem 'pg'
+  gem 'rails_12factor'
 end
```

```ruby:Gemfile
.
.
.
group :development do
  gem 'sqlite3'
end
group :production do
  gem 'pg'
  gem 'rails_12factor'
end
```

## Gemfile.lock

```bundle install``` して追加します。

## README.md

Herokuボタンを追加します。

```
[![Deploy](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy)
```

## app.json

app.json ファイルを追加します。

```json:app.json
{
  "addons": [
    "heroku-postgresql",
    "sendgrid"
  ],
  "env" : {
    "LODGE_DOMAIN"              : "example.com",
    "SECRET_KEY_BASE"           : "__some_random_string__",
    "DEVISE_SECRET_KEY"         : "__some_random_string__",
    "GOOGLE_CLIENT_ID"          : "FILL_THE_CLIENT_ID",
    "GOOGLE_CLIENT_SECRET"      : "FILL_THE_CLIENT_SECRET",
    "DELIVERY_METHOD"           : "smtp",
    "MAIL_SENDER"               : "lodge@example.com",
    "SMTP_PORT"                 : "587",
    "SMTP_AUTH_METHOD"          : "plain",
    "SMTP_ENABLE_STARTTLS_AUTO" : "true",
    "LODGE_THEME"               : "lodge"
  },
  "scripts": {
    "postdeploy": "bundle exec rake db:migrate"
  }
}
```

## config/environments/production.rb

**1. config.action_mailer.smtp_settingsの項目を変更します。**

- address
- user_name
- password

```diff
diff --git a/config/environments/production.rb b/config/environments/production.rb
index 7aa2d7b..eaa333a 100644
--- a/config/environments/production.rb
+++ b/config/environments/production.rb
@@ -93,11 +93,11 @@ Rails.application.configure do
   # SMTPの指定
   config.action_mailer.delivery_method = ENV["DELIVERY_METHOD"].to_sym
   config.action_mailer.smtp_settings = {
-    :address              => ENV["SMTP_ADDRESS"],
+    :address              => 'smtp.sendgrid.net',
     :port                 => ENV["SMTP_PORT"],
     :domain               => ENV["LODGE_DOMAIN"],
-    :user_name            => ENV["SMTP_USERNAME"],
-    :password             => ENV["SMTP_PASSWORD"],
+    :user_name            => ENV["SENDGRID_USERNAME"],
+    :password             => ENV["SENDGRID_PASSWORD"],
     :authentication       => ENV["SMTP_AUTH_METHOD"].to_sym,
     :enable_starttls_auto => ENV["SMTP_ENABLE_STARTTLS_AUTO"],
   }
```

```ruby:production.rb
.
.
.
  config.action_mailer.smtp_settings = {
    :address              => 'smtp.sendgrid.net',
    :port                 => ENV["SMTP_PORT"],
    :domain               => ENV["LODGE_DOMAIN"],
    :user_name            => ENV["SENDGRID_USERNAME"],
    :password             => ENV["SENDGRID_PASSWORD"],
    :authentication       => ENV["SMTP_AUTH_METHOD"].to_sym,
    :enable_starttls_auto => ENV["SMTP_ENABLE_STARTTLS_AUTO"],
  }
end
```

**2. config.force_sslを有効にします。（必要なら）**

```diff:production.rb
diff --git a/config/environments/production.rb b/config/environments/production.rb
index eaa333a..9e971b1 100644
--- a/config/environments/production.rb
+++ b/config/environments/production.rb
@@ -43,7 +43,7 @@ Rails.application.configure do
   # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
 
   # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
-  # config.force_ssl = true
+  config.force_ssl = true
 
   # Set to :debug to see everything in the log.
   config.log_level = :info

```

# 画像をS3に保存

[S3の特定バケットだけを"AWS Consoleを使って"操作できるIAMユーザを作る](http://qiita.com/kawaz/items/481a5af428c97ef55b14)
などを参考にさせてもらい、S3を利用可能にします。

## Gemfile

Gemfile に [fog](http://fog.io) を追加します。

```diff
diff --git a/Gemfile b/Gemfile
index 8d66364..b11cd50 100644
--- a/Gemfile
+++ b/Gemfile
@@ -62,6 +62,7 @@ gem 'compass-rails', '~> 2.0'
 #gem 'whenever', :require => false
 gem 'omniauth-google-oauth2', '~> 0.2'
 gem 'carrierwave', '~> 0.10'
+gem 'fog'
 gem 'jquery-fileupload-rails', '~> 0.4'
 
 group :development do
```

## Gemfile.lock

```bundle install``` して、ファイルを追加・コミットします。

## config/initializers/carrierwave.rb

ファイルを追加してコミットします。

```carrierwave.rb
CarrierWave.configure do |config|
  config.fog_credentials = {
    :provider               => 'AWS',
    :aws_access_key_id      => ENV['AWS_ACCESS_KEY'],
    :aws_secret_access_key  => ENV['AWS_SECRET_KEY'],
    :region                 => ENV['AWS_REGION']
  }
  config.fog_directory  = ENV['S3_BUCKET_NAME']
end
```

## app/uploaders/image_uploader.rb

file をコメントアウトして、fog を使います。

```diff
diff --git a/app/uploaders/image_uploader.rb b/app/uploaders/image_uploader.rb
index 2425faa..621956c 100644
--- a/app/uploaders/image_uploader.rb
+++ b/app/uploaders/image_uploader.rb
@@ -7,8 +7,8 @@ class ImageUploader < CarrierWave::Uploader::Base
   # include CarrierWave::MiniMagick
 
   # Choose what kind of storage to use for this uploader:
-  storage :file
-  # storage :fog
+  # storage :file
+  storage :fog
 
   # Override the directory where uploaded files will be stored.
   # This is a sensible default for uploaders that are meant to be mounted:
```

## app.json

S3アクセス用の環境変数を追加します。

```diff
diff --git a/app.json b/app.json
index 5f631e5..a1e86b7 100644
--- a/app.json
+++ b/app.json
@@ -14,7 +14,11 @@
     "SMTP_PORT"                 : "587",
     "SMTP_AUTH_METHOD"          : "plain",
     "SMTP_ENABLE_STARTTLS_AUTO" : "true",
-    "LODGE_THEME"               : "lodge"
+    "LODGE_THEME"               : "lodge",
+    "AWS_ACCESS_KEY"            : "",
+    "AWS_SECRET_KEY"            : "",
+    "AWS_REGION"                : "ap-northeast-1",
+    "S3_BUCKET_NAME"            : ""
   },
   "scripts": {
     "postdeploy": "bundle exec rake db:migrate"
```

```bash:app.json
.
.
.
    "LODGE_THEME"               : "lodge",
    "AWS_ACCESS_KEY"            : "",
    "AWS_SECRET_KEY"            : "",
    "AWS_REGION"                : "ap-northeast-1",
    "S3_BUCKET_NAME"            : ""
```