memo

ImageMagick
brew install imagemagick

RMagick install
gem install rmagick --no-rdoc --no-ri

ref
http://blog.ruedap.com/entry/20110320/mac_ruby_imagemagick_rmagick_install

Rubyで協働開発するときのコツ

1. Gemfile と Bundler を使う
Gemfile にアプリケーションに必要な Gem は全て書く。 gem install で Rails アプリケーションに必要な Gem はインストールしない。
Bundler で Gemfile に書かれた Gem をインストールする。インストール方法は bundle install --path vendor/bundle を使う。
なぜ --path 以下が必要かというと、アプリケーションディレクトリ中に Gem をインストールできるから。
gem install でインストールするとシステムグローバルになってしまうので、バージョン違いの Gem を使いたいときにネックになる。
vendor/bundle ディレクトリは .gitignore に追加しておいて、 Git の管理下から外すこと。
また、 rack や rails コマンドを使うときは bundle exec rack や bundle exec rails と読み替えること。

2. 開発サーバーには WEBrick ではなく Thin を使う
WEBrick は遅すぎて開発の妨げになる。本来のパフォーマンスを見ながら開発することが望ましいため、 Thin を使う。
Thin は Gem で提供されているため、 Gemfile の中に gem "thin" を追加すれば良い。
bundle install --path vendor/bundle でインストールした後は、 RAILS_ROOT の上で bundle exec thin start で起動する。

3. 開発環境の環境変数と、本番環境の環境変数を設定しておく
各人の Mac の環境変数には RAILS_ENV=development を設定し、本番環境には RAILS_ENV=production を設定しておく。

Unicorn
http://kanjuku-tomato.blogspot.jp/2013/02/vpscentos-63railsnginxrailsunicornpostg.html


cancan
http://sessan.hatenablog.com/entry/2012/11/12/184726

file upload
http://stackoverflow.com/questions/8268965/use-carrierwave-with-active-admin
carrierwave
http://ja.asciicasts.com/episodes/253-carrierwave-file-uploads

Ruby on Rails development with Mac OS X Mountain Lion

Most developers like to spend a bit of time setting up their workspace. I've been experimenting Ruby on Rails for some time now and this is still my preferred setup. My core criteria is simple:

Unobtrusive, no modifying core files
Flexibility with Ruby versions and gem versions per project
Minimal configuration
Easy to setup new/existing projects
So if you're a Rails developer with the same ideals this should help you get started quickly.

This article assumes a clean install of Mac OS X Mountain Lion, Mac OS X Lion could also be setup in the same way.

The Essentials

Install Xcode and Command Line Tools

Xcode is available for free from the App Store, you don't actually need it but I find the FileMerge application it comes bundled with very useful. It's a large download so be prepared to wait a little if you've not got a high-speed connection. Once it's downloaded, launch Xcode to make sure it's setup.

Now download and install the Command Line Tools for Xcode to complete the package; you need this whether you installed Xcode or not.

Install Homebrew

If you've not used Homebrew before you're going to love it. The self proclaimed missing package manager for OS X allows us to easily install the stuff we need that Apple doesn't include. Installation is simple, open Terminal (Applications » Utilities » Terminal) and copy this command:

ruby <(curl -fsSkL raw.github.com/mxcl/homebrew/go)

# Add Homebrews binary path to the front of the $PATH
echo "export PATH=/usr/local/bin:$PATH" >> ~/.bash_profile
source ~/.bash_profile
Now check our environment is correctly configured:

brew doctor
If there are any problems the doctor will give you details about the problem and sometimes even how to fix it. If not your probably not the only one so look it up in Google. Now we want to update Homebrew to make sure we're getting the latest formulas:

brew update
Install Ruby

OS X comes with Ruby installed but it's an older version (1.8.7 at time of writing), as we don't want to be messing with core files we're going to use the brilliant rbenv and ruby-build to manage and install our Ruby development environments.

Lets get brewing! We can install both using Homebrew, once done we add a line to our ~/.bash_profile and reload our terminal profile.

brew install rbenv ruby-build
echo 'eval "$(rbenv init -)"' >> ~/.bash_profile
source ~/.bash_profile
Now you'll understand why we use rbenv and ruby-build. It allows us to install different versions of Ruby and specify which version to use on a per project basis. This is very useful to keep a consistent development environment if you need to work in a particular Ruby version.

We're going to install the latest stable of Ruby (at the time of writing) you can find this out by visiting the Ruby website. Or to see a list of all available versions to install rbenv install --list.

rbenv install 2.0.0-p0
rbenv rehash
Note: You need to run the rbenv rehash after you install a new version of Ruby.

Let’s set this version as the one to use globally so we can make use of it in our terminal.

rbenv global 2.0.0-p0
You can checkout more commands in the rbenv readme on Github. It's worth bookmarking that page for reference later, or there is always rbenv --help.

Install Bundler

Bundler manages an application's dependencies, kind of like a shopping list of other libraries the application needs to work. If you're just starting out with Ruby on Rails you will see just how important and helpful this gem is.

You can use the rbenv shell command to ensure we have the correct version of Ruby loaded in our terminal window, it overrides both project-specific and global version, if you're paranoid you can always check your Ruby version with ruby --version.

rbenv shell 2.0.0-p0
gem install bundler
rbenv rehash
Notice rbenv rehash has been used again, you need to do this whenever you install a new gem that provides binaries. So if you've installed a gem and the terminal tells you it can't find it run rbenv rehash.

I like to configure Bundler to install gems in a location relative to my projects instead of globally; in this case the vendor folder of a Rails project:

mkdir ~/.bundle
touch ~/.bundle/config
echo 'BUNDLE_PATH: vendor/bundle' >> ~/.bundle/config
Skip rdoc generation

If you use Google for finding your Gem documentation like I do you might consider saving a bit of time when installing gems by skipping the documentation.

echo 'gem: --no-rdoc --no-ri' >> ~/.gemrc
That's all, as you'll see from rbenv install --list there are loads of Ruby versions available including JRuby just remember you will need to re-install your gems for each version as they are not shared.

Install SQLite3

SQLite is lightweight SQL service and handy to have installed since Rails defaults to using it with new projects. You may find OS X already provides an (older) version of SQLite3, but in the interests of being thorough we'll install it anyway as Homebrew will set it to 'keg-only' and no interfere with the system version if that is the case.

Installation is simple with Homebrew: (are you loving Homebrew yet!?)

brew install sqlite3
Install Rails

With Ruby installed and the minimum dependencies ready to go Rails can be installed as a Ruby Gem.

gem install rails
rbenv rehash
Rails has a number of dependencies to install so don't be surprised if you see loads of other gems being installed at the same time.

Your first Rails project

Ready to put all this to good use and start your first project? Good, we're going to create a new project called helloworld.

rails new helloworld
cd helloworld
Now we're going to set the local Ruby version for this project to make sure this stays constant, even if we change the global version later on. This command will write automatically to .ruby-version in your project directory. This file will automatically change the Ruby version within this folder and warn you if you don't have it installed.

rbenv local 2.0.0-p0
Now run Bundler to install all the project gems into vendor/bundle, they are kept with the project locally and won't interfere with anything else outside.

bundle install

# It's also worth updating your .gitignore file so you don't commit all of those gems!
echo '/vendor/bundle' >> .gitignore
If your gems ever stop working you can just delete the vendor/bundle directory and run the command again to re-install them.

Now let's test our application is working:

rails s
The Options Pack

Below are some extras you may wish to install. Again Homebrew to the rescue to make installation a breeze, so open your terminal and get brewing!

Note: It's recommend you run brew update before installing anything new to make sure all the formulas are up to date.

Install MySQL

One of the most commonly used SQL services, many projects end up using MySQL as a datasource. Homebrew does have formulas for alternatives such as MariaDB if you prefer.

brew install mysql
This will download and compile MySQL for you and anything else MySQL requires to work. Once finished it will give you instructions to follow regarding setting up MySQL. You can see this information any time by using the info action: brew info [package name].

# Add MySQL to launchctl to let OS X manage the process and start when you login
ln -sfv /usr/local/opt/mysql/*.plist ~/Library/LaunchAgents
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist

# Or if you want to control it yourself
mysql.server start
# Usage: mysql.server {start|stop|restart|reload|force-reload|status}

# "Secure" your MySQL installation, really it's just a handy way to clean up defaults and set a root password
mysql_secure_installation
To start a new Rails app with MySQL instead of the default SQLite3 as the datastore just use the -d flag like so:

rails new helloworld -d mysql
You can find more information about the other options available with rails --help.

ref
http://createdbypete.com/articles/ruby-on-rails-development-with-mac-os-x-mountain-lion/

Rails schemの値を変更する

type, all は予約語


ref
http://d.hatena.ne.jp/zucay/20110120/1295492571


rails generate controller controller_name index

その後 config/route.

resrouce controller_name を書く必要がある


作ったモデル、コントローラの取り消し

http://shinodogg.com/?p=3341

Rails 多対多

PostとCategoryの多対多の関係を作成する

modelの作成

rails generate scaffold Post title:string content:text
rails generate scaffold Category value:string

modelの制作

rails generate model モデル名 カラム名:データ型 カラム名:データ型

rails generate model category_post post_id:integer category_id:integer

Mac + unicorn + nginx + Rails 

環境

  • Mac OSX 10.8.3
  • Rails 3.2.13
  • Ruby 2.0.0-p0
  • Homebew

は導入済みとする

Unicorn

Install

gem install unicorn

設定

/config/unicorn.rb
を作成

# ワーカーの数
worker_processes 2

# ソケット経由で通信する
listen File.expand_path('tmp/sockets/unicorn.sock', ENV['RAILS_ROOT'])

# ログ
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

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
      # SIGTTOU だと worker_processes が多いときおかしい気がする
      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

起動

unicorn_rails -c config/unicorn.rb

その他オプション
-D デーモン化
-p ポート番号指定
-E RAILS_ENV指定

停止

Ctrl C

nginx

Install

brew install nginx

nginxへPathを通す
/usr/local/sbin/

設定ファイル

/usr/local/etc/nginx/nginx.conf
変更した所だけ記述

   upstream unicorn.rails_app{
  #自分のRailsアプリへの場所
        server unix:/Users/giwa/workspace/ror/depot/tmp/sockets/unicorn.sock fail_timeout=0;                                                                    
    } 
 
   server{
        location / {
            alias /Users/giwa/workspace/ror/depot/public;
            index  index.html index.htm index;

            try_files $uri/index.html $uri.html $uri @unicorn_rails_app;
        }

        location @unicorn_rails_app {
            proxy_redirect off;
            proxy_set_header Host               $host;
            proxy_set_header X-Real-IP          $remote_addr;
            proxy_set_header X-Forwarded-Host   $host;
            proxy_set_header X-Forwarded-Server $host;
            proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
            proxy_pass http://unicorn.rails_app;
        }

      }

neginx -t でsyntaxが正しいかチェック