Railsで特定箇所だけBASIC認証

まず全体にbasic認証(実際使う場合はEnvなどからname/paswordを取得する)

vim app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :site_http_basic_authenticate_with
  def site_http_basic_authenticate_with
    authenticate_or_request_with_http_basic("Application") do |name, password|
      name == "hoge" && password == "hoge"
    end
  end
end

特定のControllerだけskipする

skip_before_action :site_http_basic_authenticate_with

unicornの起動とnginxとの接続memo

テスト用のアプリ作成

$rails new unicorndemo -d mysql
$cd unicorndemo

gemrcの設定

vim .gemrc
gem: --no-ri --no-rdoc

gemの設定&インストール

$vim Gemfile
----------------------
gem 'unicorn'
----------------------
$bundle install --path vendor/bundler

MySQLの準備

bundle exec rake db:create
bundle exec rake db:migrate

unicorn.rbの作成

vim config/unicorn.rb
=============================================================
# -*- coding: utf-8 -*-
# ワーカーの数
worker_processes 2

# ソケット
listen  '/tmp/unicorn.sock'
pid     '/tmp/unicorn.pid'

# ログ
log = '${my_app}/log/unicorn.log'
stderr_path File.expand_path('log/unicorn.log', ENV['RAILS_ROOT'])
stdout_path File.expand_path('log/unicorn.log', ENV['RAILS_ROOT'])

preload_app true
GC.respond_to?(:copy_on_write_friendly=) and GC.copy_on_write_friendly = true

before_fork do |server, worker|
defined?(ActiveRecord::Base) and ActiveRecord::Base.connection.disconnect!

old_pid = "#{ server.config[:pid] }.oldbin"
unless old_pid == server.pid
  begin
   sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
   Process.kill :QUIT, File.read(old_pid).to_i
   rescue Errno::ENOENT, Errno::ESRCH
  end
end
end

after_fork do |server, worker|
    defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection
end
=============================================================

起動

bundle exec unicorn -c config/unicorn.rb -p 3000 -E development -D

起動確認

ps -ef | grep unicorn | grep -v grep

unicornの停止

cat /tmp/unicorn.pid
kill -QUIT <pid(tmp/unicorn.pidに記載されてるPID)>

capistranoのインストール+実行

インストール

そのままインストールする場合

$gem install capistrano
$cap -V
Capistrano Version: 3.3.5 (Rake Version: 10.4.2)

bundle installする場合はこっち

$rails new capdemo -d mysql
$cd capdemo
$bundle install --path vendor/bundler
$vim Gemfile
----------------------
gem 'capistrano'
----------------------
$bundle install --path vendor/bundler

設定ファイルの生成

$cap install / $bundle exec cap install
----------------------
#  下記ファイルが生成される
#	Capfile
#	config/deploy.rb
#	config/deploy/
----------------------

developmentの設定ファイルを作成する

$vim config/deploy/development.rb
----------------------
server 'remote.server.name', user: 'deploy', roles: %w{web}
----------------------

テスト用のtaskを記述してみる

vim config/deploy.rb
----------------------
#全部コメントアウトして下記を追加
desc "do test task"
task :test do
  on roles(:web) do
    execute "pwd"
  end
end
----------------------

テストタスクの実行

cap -T で実行されるタスクに追加されていることを確認
$cap -T 
----------------------
cap test                           # do test task
----------------------
$cap development test
----------------------
#下記のように出力されれば成功!
INFO Finished in 6.986 seconds with exit status 0 (successful).
----------------------

githubからコードをチェックアウトするタスクの作成(最低限の設定ファイルを記述)

#vim config/deploy.rb
#全部コメントアウトして下記だけ記述でOK
set :application, 'capdemo'
set :repo_url, 'git@github.com:user_name/repo_name.git'
set :deploy_to, '/var/www/capdemo/'
set :pty, true #タスク内でsudoするために必要

実行の確認

$cap -T 

実行

$cap development deploy

指定したサーバー側にディレクト

current/ releases/ repo/ revisions.log shared/
が構築され、最新のアプリはcurrentからのシンボリックリンクでreleasesに紐づけられている。


ロールバックを試してみる

//1回実行
$cap development deploy

$ll (remote側で実行)
current -> /var/www/capdemo/releases/20150201000001
releases
repo
shared

//2回目実行
$cap development deploy

$ll
current -> /var/www/capdemo/releases/20150201000002
releases
repo
shared


//ロールバックする
$cap development deploy:rollback

$ll (remote側で実行)
current -> /var/www/capdemo/releases/20150201000001
releases
repo
shared
rolled-back-release-20150201000002.tar.gz <-戻したファイルが圧縮されている

Capistranoプラグインをinstallする

本番運用に対して、

  1. gemをbundlerでインストールする
  2. データベースマイグレーションを行う
  3. Unicornを再起動する

ことをCapで一元管理することができる

Gemへ追加

vim Gemfile
group :development do
  gem "capistrano", "3.1.0
  gem "capistrano-rails"
  gem "capistrano-bundler
  gem "capistrano3-unicorn"
end

Capの設定ファイルに追加する

vim Capfile
require 'capistrano/bundler'
require 'capistrano/rails/assets'
require 'capistrano/rails/migrations'
require 'capistrano3/unicorn'

rbenv関連のコマンドが動かせるように変更する

vim config/deploy.rb
set :default_env,{
	rbenv_root: "/usr/local/rbenv",
	path: "/usr/local/rbenv/shim:/usr/local/rbenv/bin:$PATH"
}

config/deploy/development.rbに追記

set :rails_env, :development

unicornの再起動を設定


githubとの接続でerrorになった場合

>cap aborted!
>SSHKit::Runner::ExecuteError: Exception while executing as hoge@192.168.0.1: >git exit status: 128

//githubへの設定がOKか確認する
$ssh-add -l
>Could not open a connection to your authentication agent.

//agentを指定
$eval `ssh-agent`
$ssh-add id_rsaへのフルパス
($ssh-add ~/.ssh/id_rsa)

//githubに接続できるか確認する
ssh -T git@github.com
>Hi xxxx! You've successfully authenticated, but GitHub does not provide shell access.

Vagrant&VirtualBoxをインストール

vagrantに仮装環境を追加

vagrant box add centos64 http://developer.nrel.gov/downloads/vagrant-boxes/CentOS-6.4-x86_64-v20130427.box
ls ~/.vagrant.d/boxes/
vagrant box list
>centos64 (virtualbox, 0)

追加した仮装環境を起動

mkdir -p ~/Vagrant/CentOS64
cd ~/Vagrant/CentOS64/
vagrant init centos64
>Vagrantファイルが生成される.
vagrant up

仮装環境にログイン

vagrant ssh

Guest Addition の自動更新用のプラグインをinstall

vagrant plugin install vagrant-vbguest
vagrant reload

private_networkの設定(vm.networkの行をコメントアウト)

vim Vagrantfile
------------------------------------------------
  # Create a private network, which allows host-only access to the machine
  # using a specific IP.
  # config.vm.network "private_network", ip: "192.168.33.10"
  config.vm.network "private_network", ip: "192.168.33.10"
------------------------------------------------

apacheの起動+アクセス

//install
sudo yum install httpd
vim /etc/http/conf/httpd.conf
----------
#Listen Listen 80
Listen 8080
----------
sudo /etc/init.d/httpd start
sudo /etc/init.d/iptables stop

//access
http://192.168.33.10:8080/

そのほかのコマンド

[boxの削除]
vagrant box remove BOX-NAME
[boxの一覧]
vagrant box list
[boxの停止]
vagrant halt
[boxを殺す]
vagrant destroy
[boxの設定反映]
vagrant reload
[boxのステータス確認]
vagrant status

phantomjsをインストール

su -
cd /usr/local/src/
wget https://phantomjs.googlecode.com/files/phantomjs-1.9.0-linux-x86_64.tar.bz2
tar jxfv phantomjs-1.9.0-linux-x86_64.tar.bz2
cp phantomjs-1.9.0-linux-x86_64/bin/phantomjs /usr/bin/

phantomjs --version

Rails + Paperclipを試す

プロジェクトを新規作成

$rails new paperclipdemo -d mysql
$cd paperclipdemo
$bundle install --path vendor/bundler
$rails s -p80

scaffoldを作成

$rails g scaffold events name:string
$rake db:create
$rake db:migrate

Gemをupdate(PaperclipとAWS-SDKを追加する)

#vim Gemfile
----------------------
gem 'paperclip'
gem 'aws-sdk'
----------------------
$bundle install --path vendor/bundler

columnをupdateする(paperclipのコマンドを利用する)

$rails g paperclip event image
$rake db:migrate

Modelを修正する

# vim app/model/event.rb
class Event < ActiveRecord::Base
  has_attached_file :image,
    :storage => :s3,
    :s3_credentials => "#{Rails.root}/config/s3.yml",
    :path => ":attachment/:id/:style.:extension"
end

s3.ymlを作成する

# vim config/s3.yml
bucket: hogehoge
access_key_id: abcd
secret_access_key: abcd
s3_host_name: s3-ap-northeast-1.amazonaws.com

Controllerのパラメーターを修正(imageを追記)

# (これを通さないとUnpermitted parameters: imageで怒られる)
def event_params
  params.require(:event).permit(:name,:image)
end

Formテンプレートを修正

#vim app/view/events/_form.html.erb
<%= form_for(@event, :html => { :multipart => true }) do |f| %>
  <div class="field">
    <%= image_tag @event.image.url if @event.image.present? %>  
    <%= f.label :image %><br />
    <%= f.file_field :image %>
  </div>
<% end %>

Showテンプレートを修正

#vim app/view/events/show.html.erb
  <b>Image:</b>
  <%= image_tag @event.image.url if @event.image.present? %>  

resourcesメソッドを指定してRESTfulなルーティングを作る

1.Controllerの作成

$rails g controller books index show new crete edit destroy update

2.ルーティングを作成

vim config/routes.rb
=========================================
  #既に作られているルーティングをコメントアウト(削除)
  #get 'books/index'
  #get 'books/show'
  #get 'books/new'
  #get 'books/crete'
  #get 'books/edit'
  #get 'books/destroy'
  #get 'books/update'

  #resoucesを設定(index/show/new/create/edit/destroy/update全部)
  resources :books

  #resoucesを設定(show/newだけに限定したい場合)
  #resources :books, only: [:show, :new]
=========================================

3.ルーティングを確認

$rake routes
Prefix Verb   URI Pattern                Controller#Action
         books GET    /books(.:format)           books#index
               POST   /books(.:format)           books#create
      new_book GET    /books/new(.:format)       books#new
     edit_book GET    /books/:id/edit(.:format)  books#edit
          book GET    /books/:id(.:format)       books#show
               PATCH  /books/:id(.:format)       books#update
               PUT    /books/:id(.:format)       books#update
               DELETE /books/:id(.:format)       books#destroy

4.ブラウザからアクセスして確認する

http://localhost/books => Books#index
http://localhost/books/new => Books#new
http://localhost/books/1/edit => Books#edit
http://localhost/books/1 => Books#show

5その他

5-1.member,collectionを使って、アクションを追加する

memberかcollectionを用いると、index/show/new/create/edit/destroy/update以外の
アクションを追加することができる。
memberは:idがあるルートで、collectionは:idなしのルートの指定に用いられる

vim config/routes.rb
=========================================
  #resoucesを設定(index/show/new/create/edit/destroy/update全部)
  #resources :books

  resources :books do
    member do
      get 'preview'
    end

    collection do
      get 'search'
    end
  end
=========================================

ルーティングをかくにんする
previewとsearchのルーティングが追加されている。

$rake routes
Prefix Verb   URI Pattern                Controller#Action
	preview_book GET    /books/:id/preview(.:format) books#preview
	search_books GET    /books/search(.:format)      books#search

5-2.Controller名を変更する

[before]http://localhost/books --> [after]http://localhost/memos

vim config/routes.rb
=========================================
resources :users, :controller => 'members'
=========================================
$rake routes
=========================================
 memos GET    /memos(.:format)           books#index
               POST   /memos(.:format)           books#create
      new_memo GET    /memos/new(.:format)       books#new
     edit_memo GET    /memos/:id/edit(.:format)  books#edit
          memo GET    /memos/:id(.:format)       books#show
               PATCH  /memos/:id(.:format)       books#update
               PUT    /memos/:id(.:format)       books#update
               DELETE /memos/:id(.:format)       books#destroy
=========================================

segueよる画面遷移の書き方覚え書き

1.segueがpushのとき


遷移先に戻るボタンが付く



segueがmodalのとき


遷移先から戻るにはボタンを作って書く

    @IBOutlet var backButton: UIButton!
    @IBAction func backButtonPushed(sender: AnyObject) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }

ナビゲーションバーに検索窓

        var searchBar: UISearchBar!
        override func viewDidLoad() {
                super.viewDidLoad()
                searchBar = UISearchBar()
                searchBar?.searchBarStyle = UISearchBarStyle.Minimal
                searchBar?.placeholder = ""
                navigationItem.titleView = searchBar