Kinopyo Blog

プログラマとしてRuby, Rails, iPhone, iPad,Macなどなどと向き合う日々のログポース

Archive for the ‘Ruby’ Category

Ruby 1.9.3-p0 をRVMでインストール

2011年11月02日

インストール

rvm get head
rvm reload
rvm install 1.9.3-p0
rvm use 1.9.3
view raw gistfile1.sh This Gist brought to you by GitHub.

リリースノート

http://www.ruby-lang.org/ja/news/2011/10/31/ruby-1-9-3-p0-is-released/

速度

結構速くなったらしいです。

この記事を参考:http://stjhimy.com/posts/24-ruby-1-9-3-freaking-fast-bro

SinatraでStaticなHTMLファイルをrenderするには

2011年10月21日

目的

Sinatraで静的なhtmlファイルをrenderする方法です。

現状

Sinatraでは色々なビューテンプレートをレンダリングできます。Haml、Erb、Sass、Markdown、CoffeeScript…が対応されていますが、HTMLは対応してないようです。html :indexで書いてもダメですね。

Sinatraのビューテンプレート

解決方法

require 'sinatra'

get '/' do
  File.read(File.join('public', 'index.html'))
  # or
  # send_file File.join(settings.public, 'index.html')
end

File.readでファイルとして読み込むことですね。Sinatraはデフォルトの設定だとpublicフォルダ内のものをassetsとするそうです。

でちょっとリファクタリングしてhtml :indexのシンタックスでいけるようにしました。

require "sinatra"

get '/' do
  # File.read(File.join('public', 'index.html'))
  html :index
end

def html(view)
  File.read(File.join('public', "#{view.to_s}.html"))
end

参考

http://stackoverflow.com/questions/2437390/serving-static-files-with-sinatra

ruby: nil? empty? blank? どれも0をチェックしない

2011年10月18日

よくつかうメソッドの nil? empty? blank? のまとめ。

nil? すべてのオブジェクトにある。nilのときにTrueを返す。

empty? 文字の長さが0のとき、配列が空のときにTrueを返す。

blank? railsの拡張。nil, “”, ” “, [], {} のいずれかでTrueを返す。

http://ameblo.jp/ootokage/entry-10314565693.html

素晴らしいまとめですね!ootokageさんに感謝。

PHP使うときはempty(0)でtrueになりますが、上記のメソッドどれも0をチェックしないですね。。.zero?というのメソッドは一応あるようですが。

迷ったらここにいっぱいサンプルがあります。

0.nil? #=> false

0.zero? #= true

0.empty? #=> NoMethodError

0.blank? #=> false

0 == false #=> false

“”.nil? #=> false

“”.zero? #=> NoMethodError

“”.empty? #=> true

“”.blank? #=> true

“” == false #=> false

{}.nil? #=> false

{}.zero? #=> NoMethodError

{}.empty? #=> true

{}.blank? #=> true

{} == false #=> false

[].nil? #=> false

[].zero? #=> NoMethodError

[].empty? #=> true

[].blank? #=> true

[] == false #=> false

nil.nil? #=> true

nil.zero? #=> NoMethodError

nil.empty? #=> NoMethodError

nil.blank? #=> true

nil == false #=> false

false.nil? #=> false

false.zero? #=> NoMethodError

false.empty? #=> NoMethodError

false.blank? #=> true

false == false #=> true

http://underrails.seesaa.net/article/135698039.html

rspec shared_contextサンプルコード

2011年10月13日

shared_context はその名前の通りコンテキスト (テストを行なうときの状況) を共有するための機能です。

shared_context を使うことで複数箇所にちらばる同一処理をまとめることができます。shared_context は shared_context が書かれたファイルを require することでも使えるようになるので別のスペックファイルでも使うことができます。

shared_context "shared stuff" do
  before { @some_var = :some_value }
  def shared_method
    "it works"
  end
  let(:shared_let) { {'arbitrary' => 'object'} }
  subject do
    'this is the subject'
  end
end

describe "group that includes a shared context using 'include_context'" do
  include_context "shared stuff"

  it "has access to methods defined in shared context" do
    shared_method.should eq("it works")
  end

  it "has access to methods defined with let in shared context" do
    shared_let['arbitrary'].should eq('object')
  end

  it "runs the before hooks defined in the shared context" do
    @some_var.should be(:some_value)
  end

  it "accesses the subject defined in the shared context" do
    subject.should eq('this is the subject')
  end
end

Railsでcustom log(file)の作り方

2011年10月12日

Overview

rails serverで起動する時に盛りだくさんの情報がログに出力されるので、別ファイルで自分がデバッグしたい情報だけをそこに出力する方法です。この方法でtail -f log/custom.logで監視できます

ソースコード

# lib/custom_logger.rb
class CustomLogger < Logger
  def format_message(severity, timestamp, progname, msg)
    "#{timestamp.to_formatted_s(:db)} #{severity} #{msg}\n"
  end
end

logfile = File.open("#{Rails.root}/log/custom.log", 'a') # create log file
logfile.sync = true # automatically flushes data to file
CUSTOM_LOGGER = CustomLogger.new(logfile) # constant accessible anywhere
# in development.rb
require "custom_logger"
# in controller files
CUSTOM_LOGGER.info("info from custom logger")
CUSTOM_LOGGER.debug("debug from custom logger")
CUSTOM_LOGGER.error("error from custom logger")

参考

http://robaldred.co.uk/2009/01/custom-log-files-for-your-ruby-on-rails-applications/

http://ianma.wordpress.com/2009/04/08/custom-logging-in-ruby-on-rails/

Rails3.1 Capistranoでデプロイする時にpublic/images, stylesheets, javascriptsのNo such file or directoryエラー

2011年09月25日

自分のログは無くしたので@yuum3のログを引用させて頂きます。

* executing “find /home/rails_apps/todo31/releases/20110912141706/public/images /home/rails_apps/todo31/releases/20110912141706/public/stylesheets /home/rails_apps/todo31/releases/20110912141706/public/javascripts -exec touch -t 201109121417.06 {} ‘;’; true”

servers: ["176.32.95.168"]

[176.32.95.168] executing command

[err :: 176.32.95.168] find:
[err :: 176.32.95.168] `/home/rails_apps/todo31/releases/20110912141706/public/images’
[err :: 176.32.95.168] : No such file or directory
[err :: 176.32.95.168]
[err :: 176.32.95.168] find:
[err :: 176.32.95.168] `/home/rails_apps/todo31/releases/20110912141706/public/stylesheets’
[err :: 176.32.95.168] : No such file or directory
[err :: 176.32.95.168]
[err :: 176.32.95.168] find:
[err :: 176.32.95.168] `/home/rails_apps/todo31/releases/20110912141706/public/javascripts’
[err :: 176.32.95.168] : No such file or directory
[err :: 176.32.95.168]

http://d.hatena.ne.jp/yuum3/20110912

Githubにも載ってましたエラーは無視しても大丈夫そうですが、下記の一行をdeploy.rbに追記すればエラー出なくなります。

# in config/deploy.rb
set :normalize_asset_timestamps, false

Rails3.1 Production環境で画像が表示されない、HTTP Statusは200成功なのに

2011年09月24日

現象

Railsを-e productionで立ち上がるとき、或いはcapistrano本番サーバにデプロイしてアクセスする時に、HTTPのStatusは200なのに画像などが表示されない。JavascriptとCSSは問題ない。

発生バージョンはRails 3.1。

解決策

app/tmp/cacheを削除し、rake assets:precompileをもう一回実行。

ブラウザキャッシュを消してリロード。

調査経緯

assets周りの設定やfingerprint(MD5のハッシュ値)の比較など全部チェックしましたが、全然ダメでした。

最後はgithubのこのスレの方法で解決になりました。

問題となったrails applicationはRails 3.1.rc1から作っていたもので、そのままrc4, rc5, stableに更新してきました。githubで議論されたのはrc4からrc5になったときにこのような現象があったようです。恐らくtmp/cacheが変な動きをして手動で削除しない限り古いバージョンのものがずっと残されたかもしれません。

おまけ

Asset Pipelineの周りの設定ファイルを一応貼っておきます。

# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false

# Compress JavaScripts and CSS
config.assets.compress = true

# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false

# Generate digests for assets URLs
config.assets.digest = true

# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx

view raw production.rb This Gist brought to you by GitHub.

Githubでのスレ:https://gist.github.com/rails/rails/issues/2299

Rails3.1rc(?)で’Please install the mysql adapter’というエラー

2011年09月21日

確定ではないですが、Rails3.1rcにアップしたらこんなエラーが出ました。


Please install the mysql adapter: `gem install activerecord-mysql-adapter` (mysql is not part of the bundle. Add it to Gemfile.)

解決策

  • database.ymlでmysqlのadapterをmysqlよりmysql2に変更
  • Gemfileにmysql2を追加しbundle installを実行

参考

http://stackoverflow.com/questions/6141276/rails-3-1-0-rc1-mysql-adapter-error

http://stackoverflow.com/questions/3467054/problem-with-mysql2-and-rails3-bundler

REEとはRuby Enterprise Edition

Rubyのエンタープライズ版のこと。Phusion Passengerと相性がよく、メモリ消費がだいぶ下がる利点があるそうです。

rvmでの紹介を引用しますと:

Ruby Enterprise Edition, MRI Ruby with several custom

patches for performance, stability, and memory.

ガイドのドキュメント

公式サイト

現在は1.8.7が最新のようでrvmでインストールする場合は:


rvm list known

rvm install ree

Install REE with RVM

FacebookとHeroku

これはいいコンビの結成ですね。Heroku上で簡単にFacebookアプリが開発できるようになったそうです。言語も選択できるし、Herokuに慣れた人にとっては大変便利なツールだと思います。

http://blog.heroku.com/archives/2011/9/15/facebook/

Facebook/Heroku integration from heroku on Vimeo.