DRY

Web関連の技術の事、食事/お酒の事、旅行の事など

はじめてのAndroidStudio

という事でちょっと試してみました。

環境はWindows8です。

まずは、Getting Started with Android Studio | Android DevelopersからAndroidStudioをダウンロードしてきます。
でダウンロードしてきた、android-studio-bundle-130.677228-windows.exe を叩いてとりあえず適当な場所にインストールします。
私の場合は、C:\Users\[ユーザ名] の下に入れました。

ちなみにJavaIntelliJが入ってないと、そもそも論動かないのでまだの方は先に入れて下さい。
Java SE - Downloads | Oracle Technology Network | Oracle
IntelliJ IDEA — The Best Java and Polyglot IDE


見た目何かスッキリな感じで綺麗ですね。Configとか見てみるとだいぶ項目が多いなと。


早速新規プロジェクト作ってみます。
最近AndroidIDをサクっと知りたい機会が多いので、それをちょっと取るようなプロジェクトを作ってみる事にします。
※実際はProjectlocation正しいですよ(笑)

起動してみます。

こんな感じで、resいじるのも便利そうです。

それでAndroidIDを取得するために、res/layout/activity_mail.xmlを以下のように変更します。



次にMainActivity.javaを以下のように変更します。
package jp.k16.getandroidid;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

setAndroidID ();
}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

private void setAndroidID
{
String android_id = android.provider.Settings.Secure.getString (getContentResolver (), android.provider.Settings.Secure.ANDROID_ID);
Log.v ("tag", "ANDROID_ID=" + android_id);

TextView tv = (TextView)findViewById (R.id.android_id);
tv.setText ("Your Android ID is " + android_id);
}
}

でこんな感じで起動しようとしたら、
Could not execute build using Gradle distribution 'http://services.gradle.org/distributions/gradle-1.6-bin.zip'.
みたいなエラーが出るんです。

ログが C:\Users\[ユーザ名]\.AndroidStudioPreview\system\log\build-log この辺に出るらしいので見てみると
[ 365] INFO - s.builder.AndroidGradleBuilder - Using Gradle embedded mode.
[ 3956] INFO - .incremental.IncProjectBuilder - Could not execute build using Gradle distribution 'http://services.gradle.org/distributions/gradle-1.6-bin.zip'.
org.jetbrains.jps.incremental.ProjectBuildException: Could not execute build using Gradle distribution 'http://services.gradle.org/distributions/gradle-1.6-bin.zip'.

うーん。何かさっぱりわからないのでさらに調べてみると
java - Failed to import new Gradle project: Could not fetch model of type 'IdeaProject' - Stack Overflow
Android Studio and Gradle build error - Stack Overflow
みたいな話らしい。

なので、まずはGradle - Downloadsにいって、(2013/5/28時点で)最新版のgradle-1.6-bin.zipをダウンロードしてきます。
で、ここからは何回か失敗したのですが成功方法だけ記載します。

1、AndroidStudioを閉じます。
2、(私の場合はこのパス)C:\Users\[ユーザ名]\.gradle\wrapper\dists\gradle-1.6-bin\72srdo3a5eb3bic159kar72vok の中身をすべて消します。
3、C:\Users\[ユーザ名]\.gradle\wrapper\dists\gradle-1.6-bin\72srdo3a5eb3bic159kar72vok にダウンロードしてきたgradle-1.6-bin.zipをコピーします。
4、そのファイルをC:\Users\[ユーザ名]\.gradle\wrapper\dists\gradle-1.6-bin\72srdo3a5eb3bic159kar72vok 内で展開します。
5、そうするとgradle-1.6-binとgradle-1.6-bin.zipが残った状態で、AndroidStudioを再起動します。
6、再起動するとこの画面が出たのですが、removeされては困るのでチェックを外しておきます。

ちなみにこれでもうまくいかなったら、5まで終えた状態で新しいプロジェクトを作って、それを使えば問題ないかも知れません。

改めてこのような形で起動してますと、無事起動出来ました。

ちなみにEmulaterがNexus-S以外待てど暮せど立ち上がらないのですが、これはそういうものなのですかね?
まあでもxyzzyで編集してリロードかけるとすぐ修正が反映されたりで、結構いい感じですね。

とりあえず、AndroidID書き写すのめんどくさいのでメールで送れるようにします。

CentOS 6.4でPPTP VPNサーバーを構築

CentOS 6.4でPPTP VPNサーバーを構築したのでその際の設定を残しておきます。

訳あって、サーバはGlobalIPのみを持っていて、いかなるLANにも接続しません。
■環境の確認
CentOS release 6.4 (Final)


$ cat /etc/redhat-release
CentOS release 6.4 (Final)
GlobalIPのみ保持

eth0 Link encap:Ethernet HWaddr BC:30:5B:E2:8F:xx
inet addr:216.xxx.xxx.xxx Bcast:216.xxx.xxx.xxx Mask:255.255.255.240

eth1 Link encap:Ethernet HWaddr BC:30:5B:E2:8F:xx

lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:10 errors:0 dropped:0 overruns:0 frame:0
TX packets:10 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:628 (628.0 b) TX bytes:628 (628.0 b)

まずはppp関連のインストール。

# yum install ppp

# yum install pppd
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
Setting up Install Process
No package pppd available.
Error: Nothing to do
と言われるので最新版(2013年3月現在)のrpmでインストール

cd /usr/local/src
wget http://poptop.sourceforge.net/yum/stable/packages/pptpd-1.3.4-2.el6.x86_64.rpm
rpm -Uvh pptpd-1.3.4-2.el6.x86_64.rpm
そうすると、/etc/pptpd.confというファイルが出来るのでこれを編集します。
ポイントは2つで「localip」と「remoteip」

localip : PPTPでの接続後のPPTP-VPNサーバー上(つまりこのサーバー)に指定したIPアドレスが割り振られる
remoteip : PPTP-VPNクライアントに割り当てられるIPアドレスのレンジ


localip 192.168.0.240
remoteip 192.168.0.241-245
今回はファイルの一番最後にこの二つを追加しました。

次に認証方式やDNS resolverに関する設定を /etc/ppp/options.pptpdにします。
基本的にはデフォルトのままで、ms-dnsの部分だけ自分の環境に合わせます。
ms-dns 8.8.8.8
のように。

/etc/ppp/chap-secretsを編集し、このVPNサーバーにアクセスできるユーザを作成します。
フォーマットは [username] [space] [server] [space] [password] [space][IP addresses]です。
タブなどは要りません。(入れると動かないですね)


vpnuser pptpd vpnuserpassword *
※後ほど記載しますが、iptablesでアクセス元を制御するので、chap-secretsの[IP addresses]は*にしてあります。

また、IPv4転送を有効にする必要があるので、/etc/sysctl.confを変更します。


less /etc/sysctl.conf
net.ipv4.ip_forward=1
sysctl -p
一応SELinuxも確認しておきます。

# vi /etc/selinux/config
SELINUX=disabled
PPTPでは以下のポートとプロトコルを使用するので、それに見合った設定をします。
TCP/IP 1723番ポート
GRE/IP (プロトコル番号47番)

さらに今回は特定のサーバからのみ許可したいので、iptablesに以下のような設定を追加します。


-A INPUT -s 124.xx.xxx.xxx/32 -p tcp --dport 1723 -j ACCEPT
-A INPUT -s 124.xx.xxx.xxx/32 -p 47 -j ACCEPT
※124.xx.xxx.xxxからだけ許したいという状態の場合です

全体的なサービスの再起動・起動など


/etc/rc.d/init.d/iptables restart
service pptpd start
SELinux変えちゃったら再起動が必要です

起動に成功した場合以下のようにppp0がわりあたります。


# ifconfig ppp0
ppp0 Link encap:Point-to-Point Protocol
inet addr:192.168.0.240 P-t-P:192.168.0.241 Mask:255.255.255.255
UP POINTOPOINT RUNNING NOARP MULTICAST MTU:1396 Metric:1
RX packets:5797 errors:0 dropped:0 overruns:0 frame:0
TX packets:3085 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:3
RX bytes:451930 (441.3 KiB) TX bytes:1417706 (1.3 MiB)
こうなればVPN側の設定はとりあえず完了です。
後は各クライアントから接続をします。

ログを使って接続等を確認したければ、
/etc/pptpd.confのdebugを有効にして


# TAG: debug
# Turns on (more) debugging to syslog
#
debug
less /etc/rsyslog.confに"debug"を追記

*.=debug;\
news.none;mail.none -/var/log/debug
また今回は必要ないですが、VPNからInternetに出たければNATの設定をします。

iptables -t nat -A POSTROUTING -s 192.168.0.0/24 -j MASQUERADE
サブネットマスクは適当に設定してください。

AWSのCloudWatchでカスタムメトリックスを使用する

AWSのCloudWatchでカスタムメトリックスを使用する方法です。
(何番煎じになるのかな???w)

Webサーバにnginx + PHP-FPMを使ってるのでその監視とあとLoadAverageなどを追加したいのでCloudWatchをカスタマイズしました。
ずっと動かなくて困ったのですが、ミソはちゃんとRegionを伝える事でした。。。
export EC2_REGION」が楽ですね。

■参考サイト
Set Up the Command Line Interface - Amazon CloudWatch
Amazon CloudWatch で EC2 インスタンスのプロセス監視を行う - hiratake55 の開発メモ
[AWS]CloudWatchを使ってEC2を監視する方法 | 株式会社システムシンキング

■まずはCloudWatchを入手して適当な場所に配置します


wget http://ec2-downloads.s3.amazonaws.com/CloudWatch-2010-08-01.zip
unzip CloudWatch-2010-08-01.zip
cd CloudWatch-1.0.13.4/

cp credential-file-path.template credentials
cd ../
cp -a CloudWatch-1.0.13.4 /opt/aws/cloudwatch
cd /opt/aws/cloudwatch

■credentilasファイルは自分のAmazon Web Services Sign Inから
Access Key ID」と「Secret Access Key」を取ってきて入れておきます。

■適当にshellファイルに名前をつけます
(結構参考サイトからそのまま頂いてます)


vi custom_metrics.sh

以下ファイルに記載します

                                                                                                                                                                • -

#!/bin/bash

export JAVA_HOME=/usr/lib/jvm/jre
export PATH=$PATH:$JAVA_HOME/bin
export EC2_REGION=us-west-1 #私は「N.Carifolnia」を使っているのでこれになります
export AWS_CLOUDWATCH_HOME=/opt/aws/CloudWatch
export PATH=$PATH:$AWS_CLOUDWATCH_HOME/bin
export AWS_CREDENTIAL_FILE=$AWS_CLOUDWATCH_HOME/credentials

#####Config###################
# 各InstanceId
InstanceId="各InstanceIDを入力します"

#nginx and php-fpm
nginxcnt=`ps cax | grep nginx | wc -l`
phpfpmcnt=`ps cax | grep php-fpm | wc -l`
let "allcnt=nginxcnt * phpfpmcnt"
if [ "$allcnt" -gt "0" ]; then
Processes=1
else
Processes=0
fi

#Memory
memtotal=`free -m | grep 'Mem' | tr -s ' ' | cut -d ' ' -f 2`
memfree=`free -m | grep 'buffers/cache' | tr -s ' ' | cut -d ' ' -f 4`
let "memused=100 - memfree * 100 / memtotal"

#LoadAverage
loadave1=`uptime | tr -s ' ' | cut -d ' ' -f 11 | cut -d ',' -f 1`
steal=`vmstat | tail -1 | tr -s ' ' | cut -d ' ' -f 18`

#diskUsage
l_num=1
disk_max=0
df_result=/tmp/disk_usage.txt
disk_describe=/tmp/disk_describe.txt

if [ -a $df_result ]; then
rm -f $df_result
fi

df -k>$disk_describe

exec 3<$disk_describe
while read FL 0<&3
do
if [ $l_num -eq 1 ] ; then
l_num=`expr $l_num + 1`
else
echo $FL | grep /dev/ | tr -s ' ' | cut -d ' ' -f 5 | sed -e s/%// >> $df_result
fi
done
exec 3<&-

while read LINE; do
if [ $disk_max -lt $LINE ] ; then
disk_max=`expr $LINE`
fi
done<$df_result

#####Execute###################

#nginx and php-fpm
echo 'nginx and php-fpm'
mon-put-data --namespace "Custom Metrix" --metric-name "Nginx Processes" --dimensions "InstanceId=$InstanceId" --value "$Processes" --unit "Count"

#FreeMemory
echo 'FreeMemory'
mon-put-data --namespace "Custom Metrix" --metric-name "FreeMemoryMBytes" --dimensions "InstanceId=$InstanceId" --value "$memfree" --unit "Megabytes"

#UsedMemoryPercent
echo 'UsedMemoryPercent'
mon-put-data --namespace "Custom Metrix" --metric-name "UsedMemoryPercent" --dimensions "InstanceId=$InstanceId" --value "$memused" --unit "Percent"

#LoadAverage
echo 'LoadAverage'
mon-put-data --namespace "Custom Metrix" --metric-name "LoadAverage" --dimensions "InstanceId=$InstanceId" --value "$loadave1" --unit "Count"

#Steal
echo 'Steal'
mon-put-data --namespace "Custom Metrix" --metric-name "Steal" --dimensions "InstanceId=$InstanceId" --value "$steal" --unit "Percent"

#DiskUsage
echo 'DiskUsage'
mon-put-data --namespace "Custom Metrix" --metric-name "DiskUsed" --dimensions "InstanceId=$InstanceId" --value "$disk_max" --unit "Percent"
echo $disk_max

                                                                                                                                                                • -

■一応権限設定して、cronで5分に一度動くよう登録しておきます


chmod 600 credentials
chmod 755 custom_metrics.sh

crontab -e
> */5 * * * * /opt/aws/cloudwatch/custom_metrics.sh

何回かshellを試し打ちして、AWSコンソールのCloudWatchのページを見るとviewingの部分に「Custom Metrix:InstanceId」みたいな
項目が増えていれば成功です。
(反映されるまでに5分10分ぐらい待ちました。逆にそれ以上反映されていないと失敗の可能性が高いのでスクリプトの再確認が必要です)
exportの変数などを見直してみてください。



mon-put-data: Malformed input-The value 各InstanceIDを入力します for parameter
MetricData.member.1.Dimensions.member.1.Value contains non-ASCII characters.
Usage:
mon-put-data
--metric-name value --namespace value [--dimensions
"key1=value1,key2=value2..." ] [--timestamp value ] [--unit value ]
[--value value ] [--statisticValues "SampleCount=value, Sum=value,
Maximum=value, Minimum=value" ] [General Options]
For more information and a full list of options, run "mon-put-data --help"
こんな感じのエラーが出たら、単純にmon-put-dataの展開後のコマンドが間違っているので
データの型とか不正な文字列が無いかなどを見直すと良いでしょう。

ここまで出来れば後はお好きなようにAlarmを設定する感じでしょうか。
画像の例では、例えばnginxサーバのLoadAverageとDiscUseに閾値を設定しています。


Macにnginx+PHP-FPM

nginx+PHP-FPMの記事があまり無いように見えたのでエントリーしておきます。

ちなみにnginxをインストールする事自体も初めてなので合わせて。

■環境の確認
Mac Mountain Lion
最終的にはAWSにも乗せたいので基本はソースコンパイルで(一部本筋で無い部分はbrewを使用)
・nginx
PHP-FPM
CakePHP

■Reference sites
MacOSXLion10.7.5にNginxとPHP環境をソースから構築する - Web学び
GHOST IN THE SUIT - Wordpressをnginx+fastcgiベースに移行した
CakePHP 2.0開発の準備をしよう!(1/6):初心者のためのCakePHP2.0 プログラミング入門
サーバをAWS EC2+nginx+PHP+MySQLに乗り換えてみた | SUSH-i LOG
Network is unreachable

まずはwgetが無いと何も出来ないので取得しておきます


mkdir -p /usr/local/src
cd /usr/local/src
brew install wget

■PCREのインストール
元々私はPerlに慣れているので、PCREを入れておきます。
以下Web用語辞典から引用

>PCRE
>読み:ぴーしーあーるいー
>英語:Perl Compatible Regular Expressions
>意味:
>PCREとはPerl互換正規表現のことです。
>強力な文字処理能力を持つPerl正規表現は広くなじまれており、Perl正規表現に慣れた人たちは他の言語でも同じように使えるPCREは重宝します。
>Cなど他の言語にライブラリが提供されています。


wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.32.tar.gz
tar xfz pcre-8.32.tar.gz
cd /usr/local/src/pcre-8.32
./configure --enable-unicode-properties --enable-utf8
make
sudo make install

文字コード変換ライブラリICU (International Components for Unicode)のインストール


wget http://download.icu-project.org/files/icu4c/50.1.2/icu4c-50_1_2-src.tgz
tar xfz icu4c-50_1_2-src.tgz
cd /usr/local/src/icu
sh source/configure --prefix=/usr/local
gnumake
sudo make install

PHPのインストール


wget http://www.php.net/get/php-5.4.11.tar.gz/from/us1.php.net/mirror
tar xfz php-5.4.11.tar.gz

※「--enable-fpm」をしっかり入れます

cd /usr/local/src/php-5.4.11
./configure --prefix=/usr/local/php \
--enable-mbstring \
--enable-mbregex \
--enable-json \
--enable-intl \
--enable-pcntl \
--enable-fpm \
--enable-exif \
--enable-sockets \
--with-mysql --with-pdo-mysql --with-mysqli \
--with-snmp=/usr \
--with-openssl \
--with-pcre-regex=/usr/local \
--with-zlib \
--with-mhash \
--with-xmlrpc \
--with-xsl \
--with-curl \
--with-pear
make
make test
sudo make install

■CHECK


php -v
PHP 5.4.11 (cli) (built: Feb 7 2013 14:33:11)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies

■ファイルコピーなど


sudo cp /usr/local/src/php/php.ini-production /usr/local/php/lib/php.ini
cd /usr/local/php/etc
sudo cp php-fpm.conf.default php-fpm.conf

sudo ln -s /usr/local/php/bin/* /usr/local/bin/
sudo ln -s /usr/local/php/sbin/php-fpm /usr/local/bin/

export PATH=/usr/local/bin:/usr/local/sbin:$PATH

php-fpm.confの修正


sudo cp -a /private/etc/php-fpm.conf /private/etc/php-fpm.conf.old
vim /private/etc/php-fpm.conf

[global]
pid = /var/run/php-fpm.pid
error_log = /var/log/php/php-fpm.log
log_level = notice
emergency_restart_threshold = 0
emergency_restart_interval = 0
process_control_timeout = 0
daemonize = yes

[www]
listen = 127.0.0.1:9000
listen.backlog = -1
listen.allowed_clients = 127.0.0.1

;listen.owner = nginx ;Macの場合は抜いておく。For AWS
;listen.group = nginx ;Macの場合は抜いておく。For AWS
listen.mode = 0666

;user=nginx ;Macの場合は抜いておく。For AWS
;group=nginx ;Macの場合は抜いておく。For AWS

user=[ENTER YOUR USER NAME]
group=staff

pm = dynamic
pm.max_children = 10
pm.start_servers = 5
pm.min_spare_servers = 3
pm.max_spare_servers = 8
pm.max_requests = 500
pm.status_path = /status

request_slowlog_timeout = 2
request_terminate_timeout= 5
slowlog = /var/log/php/$pool.log.slow
security.limit_extensions = .php .html .css .js

■nginxのインストール


cd /usr/local/src
wget http://nginx.org/download/nginx-1.2.6.tar.gz
cd /usr/local/src/nginx-1.2.6
./configure \
--sbin-path=/usr/local/sbin/nginx \
--conf-path=/usr/local/nginx/nginx.conf \
--with-http_ssl_module \
--with-http_stub_status_module \
--without-http_upstream_ip_hash_module \
--without-http_gzip_module \
--without-http_autoindex_module \
--without-http_geo_module \
--without-http_map_module \
--without-http_split_clients_module \
--without-http_referer_module \
--without-http_proxy_module \
--without-http_uwsgi_module \
--without-http_limit_req_module \
--without-http_browser_module \
--with-pcre=../pcre-8.32
make
make install

■ファイルコピーなど


mv /usr/local/nginx-1.2.6 /usr/local/nginx
ln -s /usr/local/nginx/sbin/nginx /usr/local/bin/
sudo mkdir -p /var/log/nginx

■ここでCakePHPで動かしたいのでダウンロードと設置


cd /usr/local/src
sudo wget https://github.com/cakephp/cakephp/archive/2.2.7.tar.gz
sudo tar zxvf 2.2.7.tar.gz
mv cakephp-2.2.7 cake
mv cake /usr/local/nginx/
cakePHPは設置するだけで動きます

chmod -R 777 /usr/local/nginx/app/tmp
※app/tmpを(たぶんWebサーバの所有者が)読み書きパーミッションを変えてあげる必要がるようです。とりあえず面倒なので777で

ついでにどうせ後から言われるので、「Security.salt」 と 「chiper string」を適当に1文字ぐらい変更しておきます。
vi /usr/local/nginx/cake/app/Config/core.php

CakePHPの配置場所は「/usr/local/nginx/cake」です。


■これ前提で最後にnginx.confの修正


cp -a /usr/local/nginx/nginx.conf /usr/local/nginx/nginx.conf.old
vi /usr/local/nginx/nginx.conf

#user nginx; # Macの場合は抜いておく。For AWS
worker_processes 2;

pid /var/run/nginx.pid;

events {
worker_connections 1024;
}

http{
include /usr/local/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';

access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log;

sendfile on;
keepalive_timeout 0;
server_tokens off;


# For ELB
set_real_ip_from 10.0.0.0/8;
real_ip_header X-Forwarded-For;

server {
listen 80;
server_name localhost;
rewrite_log on;
root /usr/local/nginx/cake/app/webroot; # cakePHPの場合はwebrootをrootに
index index.php index.html index.htm;

# Not found this on disk?
# Feed to CakePHP for further processing!
if (!-e $request_filename) {
rewrite ^/(.+)$ /index.php?url=$1 last;
break;
}

location = /robots.txt { access_log off; log_not_found off; }
location = /favicon.ico { access_log off; log_not_found off; }

error_page 404 /404.html;

# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/local/nginx/html;
}

# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
#root /usr/local/nginx/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}

location = /status {
include /usr/local/nginx/fastcgi_params;
fastcgi_param SCRIPT_FILENAME /status;
fastcgi_pass 127.0.0.1:9000;
access_log off;
}

location /nginx_status {
stub_status on;
access_log off;
allow all;
deny all;
}

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
location ~ /\.ht {
deny all;
}
}
}

最後に立ち上げてみます
$ sudo php-fpm
$ sudo nginx

ちなみにnginxのコマンドは
STOP => $ nginx -s stop
RELOAD => $ nginx -s reload

一応プロセスを確認しておきますとこんな感じです
$ ps axu | grep php-fpm
nobody 37727 0.0 0.0 2477312 584 ?? S 11:07AM 0:00.00 php-fpm
nobody 37726 0.0 0.2 2481408 8936 ?? S 11:07AM 0:00.10 php-fpm
root 37725 0.0 0.0 2477312 612 ?? Ss 11:07AM 0:00.00 php-fpm

$ ps axu | grep nginx
nobody 37733 0.0 0.0 2433764 1140 ?? S 11:08AM 0:00.01 nginx: worker process
nobody 37732 0.0 0.0 2433764 1220 ?? S 11:08AM 0:00.01 nginx: worker process
root 37731 0.0 0.0 2433568 316 ?? Ss 11:08AM 0:00.00 nginx: master process nginx

最終的にhttp://localhostにておなじみの画面が出れば成功です。


Ruby on Rails + Heroku でWebサイト構築

dotcloudにRailsのプロジェクトをデプロイしようとするとtimeoutになるので(サポート問い合わせ中。。。)一旦Herokuを使う事に。

私はHerokuのアカウントは前から持っているので、登録は割愛。
Heroku | Cloud Application Platform

1. 環境の確認
Mac OSX 10.8.2 Mountain Lion

$ ruby -v
ruby 1.9.3p327 (2012-11-10 revision 37606) [x86_64-darwin12.2.0]

$ rails -v
Rails 3.2.9

$ rvm -v
rvm 1.17.0 (master) by Wayne E. Seguin , Michal Papis https://rvm.io/

Mountain LionのデフォルトのRubyは1.8.7 なので、
$ /usr/bin/ruby -v
ruby 1.8.7 (2012-02-08 patchlevel 358) [universal-darwin12.0]

1.9.3を使うために、RVMをインストール。


\curl -L https://get.rvm.io | bash -s stable --ruby
rvm get head
rvm reload
rvm use 1.9.3 --default # 1.9.3を使用してデフォルトに
インストールしたら、~/.bash_profileに以下が記載されている事を確認(無ければ追記)
-s "$HOME/.rvm/scripts/rvm" && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
eval "$(rbenv init -)"
eval "$(rbenv init -)"
eval "$(rbenv init -)"
eval "$(rbenv init -)"
eval "$(rbenv init -)"
eval "$(rbenv init -)"
eval "$(rbenv init -)"
eval "$(rbenv init -)"
eval "$(rbenv init -)"
eval "$(rbenv init -)"

or $ echo '[ [ -s "$HOME/.rvm/scripts/rvm" ] ] && . "$HOME/.rvm/scripts/rvm" # Load RVM function' >> ~/.bash_profile
# rvmの状態を確認


$ rvm list

rvm rubies

=* ruby-1.9.3-p327 [ x86_64 ]

# => - current
# =* - current && default
# * - default

2. ローカル環境にRailsアプリを作成


$ cd /Develop/Rails
$ rails new railsapp
$ cd railsapp
# Herokuで動かすために「Gemfile」のgem 'sqlite3'を変更

$ vi Gemfile
source 'https://rubygems.org'
gem 'rails', '3.2.9'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
#gem 'sqlite3'
group :production do
gem 'pg'
end
group :development, :test do
gem 'sqlite3'
end
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', :platforms => :ruby
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'
# To use Jbuilder templates for JSON
# gem 'jbuilder'
# Use unicorn as the app server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger
# gem 'debugger'
#ローカル環境の構築

$ bundle install
scaffoldを使ってテーブルを一つ作成してみておく

4. scaffoldを利用した開発(1) | TECHSCORE(テックスコア)
こちらのサイトから、scaffoldの概要を確認して同様にitemテーブルを作ってみる
$ rails g scaffold item name:string price:integer description:text
(「rails g」は「generate」の「g」らしい)


$ rails g scaffold item name:string price:integer description:text
invoke active_record
create db/migrate/20121129190553_create_items.rb
create app/models/item.rb
invoke test_unit
create test/unit/item_test.rb
create test/fixtures/items.yml
invoke resource_route
route resources :items
invoke scaffold_controller
create app/controllers/items_controller.rb
invoke erb
create app/views/items
create app/views/items/index.html.erb
create app/views/items/edit.html.erb
create app/views/items/show.html.erb
create app/views/items/new.html.erb
create app/views/items/_form.html.erb
invoke test_unit
create test/functional/items_controller_test.rb
invoke helper
create app/helpers/items_helper.rb
invoke test_unit
create test/unit/helpers/items_helper_test.rb
invoke assets
invoke coffee
create app/assets/javascripts/items.js.coffee
invoke scss
create app/assets/stylesheets/items.css.scss
invoke scss
identical app/assets/stylesheets/scaffolds.css.scss
そして、マイグレーションと呼ばれるコマンドを叩く事によって実際にテーブルが作成される、と。
なるほど。
※以下参考サイトより抜粋

マイグレーションは、railsコマンドではなく、rakeコマンドを使います。
Rakeとは、Rubyで実装されたビルドツールです。「タスク」と呼ばれる実行単位で処理を定義しておき、rakeコマンドを使って実行します。
Ruby1.9をインストールすると、同時にインストールされていますので、再度インストールする必要はありません。
Railsには、rakeコマンドで実行できるタスクが、すでにいくつか用意されています。今回行うマイグレーションもその一つです。

以下のコマンドを入力して、マイグレーションを実行します。

# マイグレーションの実行


$ rake db:migrate
== CreateItems: migrating ====================================================

    • create_table(:items)

-> 0.0205s
== CreateItems: migrated (0.0206s) ===========================================

# ローカルのRailsを起動

$ rails s
「s」は「server」の「s」だろう
http://localhost:3000/itemsをチェック
参考サイトと同じ見た目になっている事を確認

2. Herokuとの接続
# まずはHerokuコマンドのインストール

$ gem install heroku bundler
# Herokuにログイン

$ heroku login
Enter your Heroku credentials.
Email: ****@gmail.com
Password (typing will be hidden):
Authentication successful.
# パスワードを毎回聞かれなくするために、公開鍵/秘密鍵の設定

通常であれば、$ heroku keys:add だけで良いようだが、私の場合いくつものSSHの設定を持っている(社内LAN、AWSGitHub)ので
~/.ssh/configに細工が必要(最初permission deniedになりました)

なので作り直しました。ファイル名:~/.ssh/heroku_id_rsa


$ ssh-keygen -t rsa -C "***@gmail.com"
$ ssh-add
$ ssh-add -l
Could not open a connection to your authentication agent.

$ ssh-add id_dsa"
Enter passphrase for ~/.ssh/heroku_id_rsa:
Identity added: ~/.ssh/heroku_id_rsa

# 例えばこんな感じでsshのconfigを書き換える
$ vi ~/.ssh/config

Host github.com
User git
Port 22
Hostname github.com
IdentityFile ~/.ssh/github_id_rsa
TCPKeepAlive yes
IdentitiesOnly yes
Host heroku.com
User git
port 22
Hostname heroku.com
IdentityFile ~/.ssh/heroku_id_rsa
TCPKeepAlive yes
IdentitiesOnly yes

# 登録されている事を確認します。


$ ssh-add -l
1024 b4:76:79:7c:7d:41:48:a4:d1:92:c5:07:7f:22:50:71 /Users/###/.ssh/heroku_id_dsa (DSA)
# Herokuへのキー登録

$ heroku keys:add /Users/###/.ssh/heroku_id_rsa.pub
※フルパスが必要らしい
# Herokuに登録されているか確認する

$ heroku keys
ssh-rsa AIUFAxxNzaC...vBl##iVzc7 ***@gmail.com
# プロジェクトをGitの管理下にする

$ git init
$ git add .
$ git commit -m "Init Heroku Project"
# Heroku上にアプリを作成する

$ heroku create --stack cedar
# Herokuにリリースする

$ git push heroku master
git push heroku master
Counting objects: 54, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (34/34), done.
Writing objects: 100% (35/35), 4.86 KiB, done.
Total 35 (delta 6), reused 0 (delta 0)

          • > Heroku receiving push

# Heroku上でDBマイグレーション

$ heroku run rake db:migrate
Running `rake db:migrate` attached to terminal... up, run.7963
DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support for these plugins will be removed in Rails 4.0. Move them out and bundle them in your Gemfile, or fold them in to your app as lib/myplugin/* and config/initializers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonrails.org/2012/1/4/rails-3-2-0-rc2-has-been-released. (called from at /app/Rakefile:7)
DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support for these plugins will be removed in Rails 4.0. Move them out and bundle them in your Gemfile, or fold them in to your app as lib/myplugin/* and config/initializers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonrails.org/2012/1/4/rails-3-2-0-rc2-has-been-released. (called from at /app/Rakefile:7)
Connecting to database specified by DATABASE_URL
Migrating to CreateNotes (20121129181155)
Migrating to CreateItems (20121129190553)
== CreateItems: migrating ====================================================

    • create_table(:items)

NOTICE: CREATE TABLE will create implicit sequence "items_id_seq" for serial column "items.id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "items_pkey" for table "items"
-> 0.1416s
== CreateItems: migrated (0.1418s) ===========================================

# 実行

$ heroku open
最終的にターミナルに表示される「http://xxx.herokuapp.com/items」 でローカル環境(http://localhost:3000/items)と同じか確認する
※HerokuのDashBoardからも確認可能

dotcloudでlocaleエラー

久々にOSXでdotcloud動かしてみようと思い、コマンド叩いたらlocaleのエラーが出たので解決方法をメモしておきます。


$ dotcloud
Traceback (most recent call last):
File "/usr/local/bin/dotcloud", line 16, in
cli = CLI(endpoint=url, debug=debug, username=username)
File "/Library/Python/2.7/site-packages/dotcloud/ui/cli.py", line 42, in __init__
user_agent=self._build_useragent_string(),
File "/Library/Python/2.7/site-packages/dotcloud/ui/cli.py", line 72, in _build_useragent_string
(langcode, encoding) = locale.getdefaultlocale()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/locale.py", line 496, in getdefaultlocale
return _parse_localename(localename)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/locale.py", line 428, in _parse_localename
raise ValueError, 'unknown locale: %s' % localename
ValueError: unknown locale: UTF-8
exit 1
という感じでlocaleのエラーがでます。

ここに解決方法が乗っていたので、とりあえず.bash_profileで解決しました。
ValueError: unknown locale: UTF-8 · Issue #23 · dotcloud/dotcloud-cli · GitHub
正確にはMacのset localeの設定との相性のようです。


$ vi ~/.bash_profile
以下pwdの右辺を変更して記載

if [ [ $(pwd) == *yourfolderappname* ] ]
then
export LANG="en_US.UTF-8"
export LC_COLLATE="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"
export LC_MESSAGES="en_US.UTF-8"
export LC_MONETARY="en_US.UTF-8"
export LC_NUMERIC="en_US.UTF-8"
export LC_TIME="en_US.UTF-8"
export LC_ALL=
echo -e "=== CLI tweak on locale activated! ==="
fi

$ source ~/.bash_profile

$ dotcloud
nagashima@k16nagashima-no-MacBook-Pro[~/Downloads/gb_manage-master]$ dotcloud
error: too few arguments
usage: dotcloud [-h] [--application APPLICATION] [--version]

{setup,check,list,connect,disconnect,create,destroy,app,activity,info,url,status,open,run,push,deploy,dlist,dlogs,logs,env,scale,restart,domain,revisions}
...

dotcloud CLI

positional arguments:
{setup,check,list,connect,disconnect,create,destroy,app,activity,info,url,status,open,run,push,deploy,dlist,dlogs,logs,env,scale,restart,domain,revisions}
setup Setup the client authentication
check Check the installation and authentication
list List all applications
connect Connect a local directory to an existing application
disconnect Disconnect the current directory from its application
create Create a new application
destroy Destroy an existing app
app Display the application name connected to the current
directory
activity Display your recent activity
info Get information about the application or service
url Display the URL(s) for the application
status Probe the status of a service
open Open the application in the browser
run Open a shell or run a command inside a service
instance
push Push the code
deploy Deploy a specific version
dlist List recent deployments
dlogs Review past deployments or watch one in-flight
logs View your application logs or watch logs live
env Manipulate application environment variables
scale Scale services
restart Restart a service instance
domain Manage domains for the service
revisions Display all the known revision of the application

optional arguments:
-h, --help show this help message and exit
--application APPLICATION, -A APPLICATION
Specify the application
--version, -v show program's version number and exit
exit 1

Mountain Lion に Ruby 1.9.3 & Rails 3.2.8 をインストールした

OS X Mountain Lion に Homebrew + rbenv で Ruby 1.9.3 と Rails 3.2.8 をインストールしたので、そのメモを残します。

とりあえず主に参考にさせて頂いたサイトはこちらですnoanoa 日々の日記 : OS X Mountain Lion に Homebrew + rbenv で Ruby 1.9.3 をインストールした

ただ、微妙にエラーの感じが違ったりしたので、自分の分として記載しておきます。

私の環境にはXcode4.5.2が既に入ってますが、何かCommand Line Toolsを入れないとwarningが出たのでとりあえず入れます。

1.Command Line Tools をインストール
 Xcode まずインストールして、Xcode のメニュー > Preferences からダウンロードしてインストールする。

※Command Line Toolsの他のインストール方法は多くのサイトに載っていますので参照下さい。


2. Homebrewのインストール


$ /usr/bin/ruby -e "$(/usr/bin/curl -fsSL https://raw.github.com/mxcl/homebrew/master/Library/Contributions/install_homebrew.rb)"
curl: (22) The requested URL returned error: 404
幾つかのサイトにあるコマンドをコピーしたのですが、404エラーが出るのでRedirecting...で直接確認したら、下記のコマンドだったので、貼り直して無事開始

$ ruby -e "$(curl -fsSkL raw.github.com/mxcl/homebrew/go)"

  • e:67: warning: Insecure world writable dir /Users/nagashima/Develop in PATH, mode 040757
  • e:88: warning: Insecure world writable dir /Users/nagashima/Develop in PATH, mode 040757

==> This script will install:
/usr/local/bin/brew
/usr/local/Library/...
/usr/local/share/man/man1/brew.1

Press ENTER to continue or any other key to abort

  • e:34: warning: Insecure world writable dir /Users/nagashima/Develop in PATH, mode 040757

==> Downloading and Installing Homebrew...
remote: Counting objects: 89578, done.
remote: Compressing objects: 100% (41611/41611), done.
remote: Total 89578 (delta 62414), reused 71609 (delta 47125)
Receiving objects: 100% (89578/89578), 12.92 MiB | 2.44 MiB/s, done.
Resolving deltas: 100% (62414/62414), done.
From https://github.com/mxcl/homebrew
* [new branch] master -> origin/master
Checking out files: 100% (2489/2489), done.
HEAD is now at 2e65c80 elinks 0.12pre6
==> Installation successful!
You should run `brew doctor' *before* you install anything.
Now type: brew help

# まずはbrew doctorをすべしとの指示なので


$ brew doctor
Warning: You have Macports or Fink installed.
This can cause trouble. You don't have to uninstall them, but you may like to
try temporarily moving them away, eg.

sudo mv /opt/local ~/macports
Warning: Unbrewed dylibs were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.

Unexpected dylibs:
/usr/local/lib/libntfs-3g.76.dylib /usr/local/lib/libntfs.9.0.0.dylib /usr/local/lib/libpng15.15.dylib /usr/local/lib/librpm-5.0.dylib /usr/local/lib/librpmbuild-5.0.dylib /usr/local/lib/librpmconstant-5.0.dylib /usr/local/lib/librpmdb-5.0.dylib /usr/local/lib/librpmio-5.0.dylib /usr/local/lib/librpmmisc-5.0.dylib /usr/local/lib/libublio.1.dylib /usr/local/lib/libz.1.2.7.dylib
Warning: Unbrewed .la files were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.

Unexpected .la files:
/usr/local/lib/libntfs-3g.la /usr/local/lib/libntfs.la /usr/local/lib/libpng15.la /usr/local/lib/libublio.la
Warning: Unbrewed .pc files were found in /usr/local/lib/pkgconfig.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.

Unexpected .pc files:
/usr/local/lib/pkgconfig/fuse.pc /usr/local/lib/pkgconfig/libntfs-3g.pc /usr/local/lib/pkgconfig/libpng15.pc /usr/local/lib/pkgconfig/libublio.pc /usr/local/lib/pkgconfig/rpm.pc /usr/local/lib/pkgconfig/zlib.pc
Warning: Unbrewed static libraries were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.

Unexpected static libraries:
/usr/local/lib/libntfs-3g.a /usr/local/lib/libntfs.a /usr/local/lib/libpng15.a /usr/local/lib/libublio.a /usr/local/lib/libz.a
Warning: You have a non-Homebrew 'pkg-config' in your PATH:
/opt/local/bin/pkg-config

`./configure` may have problems finding brew-installed packages using
this other pkg-config.
exit 1

多数warningが出ました。

上から順に対応方法は
#1 指示されたコマンドの通りに


$ sudo mv /opt/local ~/macports
Password:
#2 該当ファイルの削除

rm -fr /usr/local/lib/libntfs-3g.76.dylib
rm -fr /usr/local/lib/libntfs.9.0.0.dylib
rm -fr /usr/local/lib/libpng15.15.dylib
rm -fr /usr/local/lib/librpm-5.0.dylib
rm -fr /usr/local/lib/librpmbuild-5.0.dylib
rm -fr /usr/local/lib/librpmconstant-5.0.dylib
rm -fr /usr/local/lib/librpmdb-5.0.dylib
rm -fr /usr/local/lib/librpmio-5.0.dylib
rm -fr /usr/local/lib/librpmmisc-5.0.dylib
rm -fr /usr/local/lib/libublio.1.dylib
rm -fr /usr/local/lib/libz.1.2.7.dylib
#3 該当ファイルの削除

rm -fr /usr/local/lib/libntfs-3g.la
rm -fr /usr/local/lib/libntfs.la
rm -fr /usr/local/lib/libpng15.la
rm -fr /usr/local/lib/libublio.la
#4 該当ファイルの削除

rm -fr /usr/local/lib/libntfs-3g.a
rm -fr /usr/local/lib/libntfs.a
rm -fr /usr/local/lib/libpng15.a
rm -fr /usr/local/lib/libublio.a
rm -fr /usr/local/lib/libz.a
#5 Monoについて確認
masahiro-yanai: macports更新とhomebrewインストールによるとMonoが悪さをしているようで、私の環境にもMonoが入っているのでスクリプトを試してみる

実際のスクリプトMono:OSX - Monoに記載されている


#!/bin/sh -x

#This script removes Mono from an OS X System. It must be run as root

rm -r /Library/Frameworks/Mono.framework

rm -r /Library/Receipts/MonoFramework-*

for dir in /usr/bin /usr/share/man/man1 /usr/share/man/man3 /usr/share/man/man5; do
(cd ${dir};
for i in `ls -al | grep /Library/Frameworks/Mono.framework/ | awk '{print $9}'`; do
rm ${i}
done);
done

#でこのスクリプトを実行

sudo vi /bin/uninstall_mono.sh
sudo chmod 755 /bin/uninstall_mono.sh
sudo /bin/uninstall_mono.sh
#再度doctorの診断を

$ brew doctor
Warning: Unbrewed .pc files were found in /usr/local/lib/pkgconfig.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.

Unexpected .pc files:
/usr/local/lib/pkgconfig/fuse.pc /usr/local/lib/pkgconfig/libntfs-3g.pc /usr/local/lib/pkgconfig/libpng15.pc /usr/local/lib/pkgconfig/libublio.pc /usr/local/lib/pkgconfig/rpm.pc /usr/local/lib/pkgconfig/zlib.pc
exit 1

#再び該当ファイルの削除

rm -fr /usr/local/lib/pkgconfig/fuse.pc
rm -fr /usr/local/lib/pkgconfig/libntfs-3g.pc
rm -fr /usr/local/lib/pkgconfig/libpng15.pc
rm -fr /usr/local/lib/pkgconfig/libublio.pc
rm -fr /usr/local/lib/pkgconfig/rpm.pc
rm -fr /usr/local/lib/pkgconfig/zlib.pc

$ brew doctor
Your system is raring to brew.
#これで診断はすべて問題なくなったので、念のためupdateも確認

$ brew update
Already up-to-date.

3.rbenv と ruby-buildのインストール


$ brew install rbenv
$ brew install ruby-build
==> Downloading https://github.com/sstephenson/rbenv/tarball/v0.3.0
Already downloaded: /Library/Caches/Homebrew/rbenv-0.3.0.tgz
Warning: The cleaning step did not complete successfully
Still, the installation was successful, so we will link it into your prefix
==> Caveats
To enable shims and autocompletion add to your profile:
if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi

To use Homebrew's directories rather than ~/.rbenv add to your profile:
export RBENV_ROOT=/usr/local/opt/rbenv
Warning: This keg was marked linked already, continuing anyway
==> Summary
/usr/local/Cellar/rbenv/0.3.0: 32 files, 168K, built in 2 seconds

#rbenvの設定を.bash_profileに追加する。

$ vi ~/.bash_profile

  1. # Ruby
  2. echo 'eval "$(rbenv init -)"' >> .bash_profile

$ source ~/.bash_profile

#rbenv の設定をいろいろ変えたときは、そのつど反映させるためには rehash が必要だとの事なので
$ rbenv rehash

4.ruby をインストールreadline と OpenSSL のライブラリをインストールしておく必要があるとの事なので


$ brew install readline
==> Downloading http://ftpmirror.gnu.org/readline/readline-6.2.tar.gz
######################################################################## 100.0%
==> Patching
patching file callback.c
patching file input.c
patching file patchlevel
patching file support/shobj-conf
patching file vi_mode.c
==> ./configure --prefix=/usr/local/Cellar/readline/6.2.4 --mandir=/usr/local/Cellar/readline/6.2.4/share/
brew link readline

brew install openssl
brew link openssl
^[[A^[[B==> make install
==> Caveats
This formula is keg-only: so it was not symlinked into /usr/local.

OS X provides the BSD libedit library, which shadows libreadline.
In order to prevent conflicts when programs look for libreadline we are
defaulting this GNU Readline installation to keg-only.

Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:

LDFLAGS: -L/usr/local/opt/readline/lib
CPPFLAGS: -I/usr/local/opt/readline/include

==> Summary
/usr/local/Cellar/readline/6.2.4: 31 files, 1.8M, built in 42 seconds
$ brew link readline
Linking /usr/local/Cellar/readline/6.2.4... 12 symlinks created
$
$ brew install openssl
==> Downloading http://openssl.org/source/openssl-1.0.1c.tar.gz
######################################################################## 100.0%
==> perl ./Configure --prefix=/usr/local/Cellar/openssl/1.0.1c --openssldir=/usr/local/etc/openssl zlib-dy
==> make
==> make test
==> make install MANDIR=/usr/local/Cellar/openssl/1.0.1c/share/man MANSUFFIX=ssl
==> Caveats
This formula is keg-only: so it was not symlinked into /usr/local.

Mac OS X already provides this software and installing another version in
parallel can cause all kinds of trouble.

The OpenSSL provided by OS X is too old for some software.

Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:

LDFLAGS: -L/usr/local/opt/openssl/lib
CPPFLAGS: -I/usr/local/opt/openssl/include

==> Summary
/usr/local/Cellar/openssl/1.0.1c: 429 files, 15M, built in 4.9 minutes
$ brew link openssl
Linking /usr/local/Cellar/openssl/1.0.1c... 1139 symlinks created

#インストール可能な Ruby のバージョンを確認


$ rbenv install -l
Available versions:
1.8.6-p383
1.8.6-p420
1.8.7-p249
1.8.7-p302
1.8.7-p334
1.8.7-p352
1.8.7-p357
1.8.7-p358
1.8.7-p370
1.9.1-p378
1.9.2-p180
1.9.2-p290
1.9.2-p318
1.9.2-p320
1.9.3-dev
1.9.3-p0
1.9.3-p125
1.9.3-p194
1.9.3-p286
1.9.3-p327
1.9.3-preview1
1.9.3-rc1
2.0.0-dev
2.0.0-preview1
jruby-1.5.6
jruby-1.6.3
jruby-1.6.4
jruby-1.6.5
jruby-1.6.5.1
jruby-1.6.6
jruby-1.6.7
jruby-1.6.7.2
jruby-1.6.8
jruby-1.7.0
jruby-1.7.0-preview1
jruby-1.7.0-preview2
jruby-1.7.0-rc1
jruby-1.7.0-rc2
maglev-1.0.0
maglev-1.1.0-dev
rbx-1.2.4
rbx-2.0.0-dev
rbx-2.0.0-rc1
ree-1.8.6-2009.06
ree-1.8.7-2009.09
ree-1.8.7-2009.10
ree-1.8.7-2010.01
ree-1.8.7-2010.02
ree-1.8.7-2011.03
ree-1.8.7-2011.12
ree-1.8.7-2012.01
ree-1.8.7-2012.02

#ここで、新しいバージョンの Ruby が表示されないときは、ruby-build を upgrade すると良いとの事
なので念の為実行


$ brew upgrade ruby-build
Error: ruby-build-20121120 already installed

# 更新されるようであればrehash を忘れずに!
rbenv rehash
rbenv instal

the latest and greatest version をインストールすべしとの事みたいなので
「1.9.3-p327」をチョイス


$ rbenv install 1.9.3-p327
Downloading yaml-0.1.4.tar.gz...

Installing yaml-0.1.4...
Installed yaml-0.1.4 to /Users/nagashima/.rbenv/versions/1.9.3-p327

Downloading ruby-1.9.3-p327.tar.gz...

Installing ruby-1.9.3-p327...
Installed ruby-1.9.3-p327 to /Users/nagashima/.rbenv/versions/1.9.3-p327

exit 1

#インストールされているバージョンを確認


$ rbenv versions
1.9.3-p327

5.rails をインストール


$ gem install rails
ERROR: While executing gem ... (Gem::FilePermissionError)
You don't have write permissions into the /Library/Ruby/Gems/1.8 directory.
exit 1
#おいっ!って事なんですが、実は$ gem install rails打った後にとにかく待ちます。
プロンプトが何の反応も無いので、止まってるように見えますが動いてます。
(事実私も何回か、Crtl+Cしちゃいました。。。)



$ sudo gem install rails
Password:

# 約10分後 ------>

Building native extensions. This could take a while...
Depending on your version of ruby, you may need to install ruby rdoc/ri data:<= 1.8.6 : unsupported
= 1.8.7 : gem install rdoc-data; rdoc-data --install
= 1.9.1 : gem install rdoc-data; rdoc-data --install
>= 1.9.2 : nothing to do! Yay!
Successfully installed i18n-0.6.1
Successfully installed multi_json-1.3.7
Successfully installed activesupport-3.2.9
Successfully installed builder-3.0.4
Successfully installed activemodel-3.2.9
Successfully installed rack-1.4.1
Successfully installed rack-cache-1.2
Successfully installed rack-test-0.6.2
Successfully installed journey-1.0.4
Successfully installed hike-1.2.1
Successfully installed tilt-1.3.3
Successfully installed sprockets-2.2.1
Successfully installed erubis-2.7.0
Successfully installed actionpack-3.2.9
Successfully installed arel-3.0.2
Successfully installed tzinfo-0.3.35
Successfully installed activerecord-3.2.9
Successfully installed activeresource-3.2.9
Successfully installed mime-types-1.19
Successfully installed polyglot-0.3.3
Successfully installed treetop-1.4.12
Successfully installed mail-2.4.4
Successfully installed actionmailer-3.2.9
Successfully installed rake-10.0.2
Successfully installed rack-ssl-1.3.2
Successfully installed thor-0.16.0
Successfully installed json-1.7.5
Successfully installed rdoc-3.12
Successfully installed railties-3.2.9
Successfully installed bundler-1.2.2
Successfully installed rails-3.2.9
31 gems installed

#一応確認


$ rails -v
Rails 3.2.9
という事で無事すべてインストール出来たようです。