#rails #ruby #postgresql #rspec

PostgresSQLでrake specするとNOTICEがいっぱいでるが大変参考になった。

NOTICE: CREATE TABLE will create implicit sequence “peroperos_id_seq” for serial column “peroperos.id” NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index “peroperos_pkey” for table “peroperos” ~略~

の警告をシャットダウンする方法です。

#rails #ruby #rack #troubleshooting

Rails 3.1以前のバージョンなら多分テスト実行時にこういう警告が出ることがあるかもしれません。

gems/rack-1.2.5/lib/rack/utils.rb:16: warning: regexp match /.../n against to UTF-8 string

このうるさい警告を消す方法を紹介します。

解決方法

rspecを使う場合はspec/spec_helper.rbに下記コードを最後に追記してください。

原因

Rack1.3からは解決できたらしいですが、Rails 3.1以前を使うならとりあえずこの方法で回避してもいいかと。 詳しくは:https://github.com/rack/rack/issues/41

#rails #ruby #asset

ActionView/Helpers/AssetTagHelper、asset(画像、CSSなど)ホストのチューニングについての勉強メモです。

asset hostを指定

image_tag(“rails.png”)のhelper methodで生成するリンクはデフォルトでは同じホストのpublicフォルダを指しています。それを変更したい場合はconfig/environments/production.rbActionController::Base.asset_hostをいじります。

ActionController::Base.asset_host = "assets.example.com"
image_tag("rails.png")
# => <img alt="Rails" src="http://assets.example.com/images/rails.png?1230601161" />

asset hostを複数指定

ブラウザが一度に同一サーバには2つのコネクションしかできないそう(これは初めて知りました)で、asset同士のダウンロード完了するのを待たなければなりません。もし複数台のassetサーバがある場合はassets%d.example.comを使ってそれをコネクション数を増やせることができます。%dが指定されればRailsは0~3の4つの番号を付けて、並行して8つのコネクションができます。

ActionController::Base.asset_host = "assets%d.example.com"
image_tag("rails.png")
# => <img alt="Rails" src="http://assets.example.com/images/rails.png?1230601161" />
stylesheet_link_tag("application")
# => <link href="http://assets2.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" />

カスタマイズ

もっと自分でカスタマイズしたい場合はsourceのprocパラメータを使えます。

ActionController::Base.asset_host = Proc.new { |source|
  "http://assets#{Digest::MD5.hexdigest(source).to_i(16) % 2 + 1}.example.com"
}
image_tag("rails.png")
# => <img alt="Rails" src="http://assets1.example.com/images/rails.png?1230601161" />
stylesheet_link_tag("application")
# => <link href="http://assets2.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" />

特定のパスで始まるassetを特定のホストに指定する例:

ActionController::Base.asset_host = Proc.new { |source|
   if source.starts_with?('/images')
     "http://images.example.com"
   else
     "http://assets.example.com"
   end
 }
image_tag("rails.png")
# => <img alt="Rails" src="http://images.example.com/images/rails.png?1230601161" />
stylesheet_link_tag("application")
# => <link href="http://assets.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" />

さらにrequestの第二パラメータもあります。これでHTTPSの動作も制御できます。

ActionController::Base.asset_host = Proc.new { |source, request|
  if request.ssl?
    "#{request.protocol}#{request.host_with_port}"
  else
    "#{request.protocol}assets.example.com"
  end
}

Resources

http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html

#actionview #rails #ruby #partial

例えば省略可能なフラグみたいなローカル変数をpartial viewに渡した時、そのデフォルト動作をpartial viewでハンドリングしたいですね。

調べてみたらdefined?local_assigns.has_key?が見つかりましたが、前者のほうはオススメできなさそうです。

Testing using defined? headline will not work. This is an implementation restriction. http://api.rubyonrails.org/classes/ActionView/Base.html

実際やってみて、defined?でも動けるパターンはありますが、if/unless文で一行にしたらバグりました。なのでやはり* local_assigns.has_key?*を使いましょう。

Resources

http://stackoverflow.com/questions/238615/defined-method-in-ruby-and-rails http://api.rubyonrails.org/classes/ActionView/Base.html

#rails #ruby #capybara #rspec #webkit

Goal

ゴールと言うか目標はrspecのrequest(integration) testでjavascriptのテストをしたいです。が、いろいろハマってその問題と解決策を時間軸でメモしておきます。

Capybaraについてはある程度知ってる前提です。

javascriptのテストを書く

:js => trueでrspecのintegration testでjavascriptを有効に設定できます。 例:

ただデフォルトではjavascriptをサポートしないので、このspecは失敗します。解決の鍵はcapybara driverというものです。

capybara_webkit driver

なぜcapybara_webkit driver使う

Capybara … currently comes with Rack::Test and Selenium support built in.

By default, Capybara uses the :rack_test driver, which is fast but does not support JavaScript. You can set up a different default driver for your features.

The capybara-webkit driver is for true headless testing. It uses QtWebKit to start a rendering engine process. It can execute JavaScript as well. It is significantly faster than drivers like Selenium since it does not load an entire browser.

のようにcapybaraは Rack::TestSeleniumのdriverがbuilt-inされて、デフォルトdriverは前者の:rack_testでjavascriptをサポートしないです。Seleniumはサポートしますが、それよりも速いのがcapybara-webkitなのでそれを採用しました。

capybara_webkit driverをインストール

Gemfileにcapybara_webkitを追記、bundle installします。webkitはQTが必要なので、もしそれがないとbundle installで失敗(エラー)します。後はspec_helper.rbにdefault driverをwebkitに設定します。

これで最初のサンプルspecは通るはずです。

データベースと絡んだテスト

上記のままだとデータベースと絡んだテストはまた失敗します。 例:

自分で確認してみたら、テスト時に作成したデータはjavascriptのテストで使えないっぽいです。Railscastsの記事によりますとspecのテストではデータベーストランザクションを使うが、それがselenium或いはwebkitでは使えないそうです。そのためにdatabase_cleanerというgemを使います。

database_cleanerを使う

config.use_transactional_fixturesをfalseにした時点でもうテスト自体は通るはずですが、データはずっとそのまま残ってしまうんです。database_cleanerは名の通りデータベースをテスト前後で綺麗な状態に保つことができます。

これでもう環境面の設定は完了です!

Resources

目的

OmniauthでTwitterに認証ログイン後、ログイン前と同じページにリダイレクトしたい

方法

libディレクトリのautoloadはRails libディレクトリのファイルをautoloadを参考してください。

解説

redirect_toパラメータ或いはrefererをログイン直前のリクエストから取ってセッションに保存するRack middwareの手法です。そしてsessions_controllerではセッション内に保存されたurlにリダイレクトし、セッションクリアしています。

もちろんTwitter以外のproviderでの認証&ログイン処理にも対応できます。

#ruby #sinatra

目的

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

現状

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

Sinatraのビューテンプレート

解決方法

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

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

参考

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

#ruby

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

nil? すべてのオブジェクトにある。nilのときにTrueを返す。 empty? 文字の長さが0のとき、配列が空のときにTrueを返す。

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

素晴らしいまとめですね!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

日本語

shared_context はその名前の通りコンテキスト (テストを行なうときの状況) を共有するための機能です。 shared_context を使うことで複数箇所にちらばる同一処理をまとめることができます。shared_context は shared_context が書かれたファイルを require することでも使えるようになるので別のスペックファイルでも使うことができます。

#rails #ruby #log

Overview

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

ソースコード

参考

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/

自分のログは無くしたので@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*

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

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

現象

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の周りの設定ファイルを一応貼っておきます。

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

#ruby #ree #rvm

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

#ruby #rails3.1 #troubleshooting

確定ではないですが、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

#ruby #metaprogramming

下記ソースコードに英語コメントで書いてますが、日本語で解釈してみます。

定義

まずinstance_evalはObjectのインスタンスメソッドです。なので全てのオブジェクトがこのinstance_evalを呼び出すことができます。instance_evalはブロックを受け取ります。

機能

  • 呼び出すオブジェクト(receiver)のスコープ内でブロックを評価(実行)する、つまりreceiverのプライベートメソッドやインスタンス変数にアクセスできること
  • 現在スコープの変数などBindingにアクセスできる

サンプルコードではPersonというclassに@nameのインスタンス変数、credit_cardというプライベートメソッドを定義しました。

someoneはPersonのインスタンスで、someoneからinstance_evalをコールすると、そのブロック内ではselfがsomeoneとなり、@nameやcredit_cardにアクセスできます。

さらにinstance_evalの外で定義した変数outter_valにもアクセスできます。

Real-life example

さて、原理は分かったとして、実際はどのように使われているのか、Railsのソースコードでgrepしてこんなコードが見つかりました。

in ActiveRecord

まずマイグレーションでまあよく使うchange_columnメソッドのソースコードです。

definition[column_name]がinstance_evalを呼び出したのですが、definition[column_name]はActiveRecord::ConnectionAdapters::ColumnDefinitionクラスのオブジェクトで、ColumnDefinitionの実態はStructを継承し、カラムの名前、種類、limit、precision、デフォルト値などの情報が格納されているオブジェクトです。

definition[column_name].instance_evalを使うことで、そのオブジェクト(テーブルカラム)の種類、limit、default値とnull可否を変更することが分かりましたね。 optionsはinstance_evalブロックの外の変数ですが、普通にアクセスできます。

in ActiveSupport

上記ActiveRecordのコードが分かればここは分かりやすいと思います。 実際の意味はさておき、instance_evalを利用して@marshal_with_utc_coercionというインスタンス変数が定義されていれば、それを削除する使い方ですね。

まとめ

instance_evalを使ってオブジェクトの構造(インスタンス変数の値の変更、インスタンス変数の追加削除など)を実行時に変更するのが使い道、というのが個人的な感想です。

最後に注記:この記事はRails3.1.0のソースコードを使ってます。

#ruby #metaprogramming

Rubyのクラスにメソッドを追加する方法です。ここではStringを例にしました。

solution_1.rbはOpen Classというテクニックです。classキーワードで既存クラスを定義するときは上書きするのではなく、拡張した感じで、他のStringメソッドに影響がないです。

solution_2.rbはただclass_evalの理論を試したかっただけです。class_evalはスコープ内のselfcurrent classをreceiverのStringクラスに変更するんです。だからclass_evalのブロック内に定義したメソッドはStringのinstance methodになります。

solution_mistake.rbはStringのクラスメソッド(Singleton methods)を定義したもので、instance methodではないです。

最近「Metaprogramming Ruby」という本を読んでます。よくわからなかったこととか、曖昧だっだことがすっきりした感じです。お勧めです!

#ruby #rvm #環境構築

ruby 1.9.2p290へ更新しました。rvmもついでに。

# update rvm  
$ rvm get head  
# or older versions such as 1.0.0  
$ rvm update --head  
# you need to run reload to reflect the update  
$ rvm reload         
$ rvm -v
  rvm 1.7.2 by Wayne E. Seguin (wayneeseguin@gmail.com) [https://rvm.beginrescueend.com/]

# install ruby 1.9.2.p290  
$ rvm install 1.9.2-p290
  ...  
$ rvm list
  ruby-1.9.2-p0
  ruby-1.9.2-p180  
# you need to replace the p0 based on your environment  
$ rvm upgrade ruby-1.9.2-p0 ruby-1.9.2-p290
yes  
yes  
yes  ...  
Upgrade complete!  
$ rvm list
  ruby-1.9.2-p290 [ x86_64 ]  
$ rvm --default use 1.9.2
$ ruby -v
  ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin10.8.0]
#ruby #https #nokogiri

Nokogiriでurlをparseするときは普通こんなコードになります。

doc = Nokogiri::HTML(open('http://example.com/'))

しかし接続先のプロトコールがhttpsの場合はNo such file or directoryのエラーとなります。 一旦net/httpsで取ってからそれをnokogiriでparseするような工夫が必要です。

#ruby #heroku #memcached #sinatra

昨日の記事https://kinopyo.com/ja/blog/a-sintra-app-to-grab-funny-images-from-a-github-thread/にも簡単に述べましたが、DalliはHerokuでお勧められているMemcachedのGemです。正確にはpure ruby memcache-clientです。

インストールと使い方をGistで公開しています。

参考サイト: http://devcenter.heroku.com/articles/memcache https://github.com/mperham/dalli

スレット経緯

bumblebeeというgithubのプロジェクトにinstall.shというファイルがありますが、 実行するとrm -rf /usrのコマンドで/usrが全部削除されることで大騒ぎになったようです。 githubのスレット

bumblebee rm -rf :usr

一個スペースが多かったですね。。

でコメントに上がっている画像がとても面白かったので、それをNokogiriを使って拾うrubyコードを書きました。プログラマのヒューモア満載の画像ですね。

Sinatra + Nokogiri + Herokuで作りました、キャッシュはdalliというgemを使いました。

成果

下記iframeで表示しています。urlはhttp://kinopyo-omgmyusr.heroku.com

ソースコード

githubに上げています。 https://github.com/kinopyo/Funny-Images-in-bumblebee-rm–rf–usr-thread

参考になったリンク: http://devcenter.heroku.com/articles/memcache

#rails #ruby #heroku #rails3.1

この前Herokuのドキュメントを見ましたが、まだRails3.0.7しか正式にサポートされているようです。でも実はRails 3.1rcもherokuで実行できますよ。

上記snippetはgistで保管しJavaScriptで表示しています。RSSでご覧の方は見れないと思います。お手数ですが、直接アクセスしてください。

#ruby #sinatra

Sinatra使って二日目ですが、サーバーを再起動しないと修正したコードが反映されないことに気づきました。これは不便なので、改善する方法を紹介します。

shotgunというgemを使えばOKです。インストールし、ruby -rubygemsではなくshotgunでサーバを起動します。

$ sudo gem install shotgun
$ shotgun myapp.rb
== Shotgun/WEBrick on http://127.0.0.1:9393/
...

これでサーバを再起動せずにホットデプロイができるようになります。

他にもSinatra::ReloaderSinatra::Reloaderが公式サイトで紹介されていますが、shotgunは一番簡単だそうです。

参考サイト: http://stackoverflow.com/questions/5684266/can-i-do-sinatra-program-without-restart-server What happened to reloading in Sinatra

#ruby #mac #sinatra #環境構築

Sinatraを試したところこのようなエラーになりました。

ruby -rubygems myapp.rb
no such file to load -- ubygems (LoadError)

ググッてみたらやはりPATHが間違ったっぽいです。 Macportでrubygemsをインストールすることで解決できるそうです。 その後はgemを再度インストールする必要があるらしいです。 操作の流れ:

#パスの確認
which gem
/usr/bin/gem

sudo port install rb-rubygems
...
# Terminal再起動
# パスの確認
which gem
/opt/local/bin/gem

sudo gem install sinatra

一旦はこれで解決です。

参考になったサイト: http://d.hatena.ne.jp/holypp/20110319/1300556202 http://d.hatena.ne.jp/Kuna/20090315/1237121262

#rails #ruby #rails3.1

Rails3.1.0 beta1をインストールするときにあったトラブルです。

インストール

// 3.1.0 betaに更新
sudo gem install rails --pre

// バージョン確認
rails -v

// ダミープロジェクト作成
rails new railsfoo

// 必要なGemをインストール
cd railsfoo
bundle install

// サーバ起動
rails s

トラブル

ここまで順調でしたが、http://127.0.0.1:3000にアクセスしたときにundefined method `context’ for #<Sprockets::Environment:>のトラブルに会いました。

Sprockets trouble

どうやらこのSprocketsというのがポイントのようです。 ぐぐってみたらgithubでこのようなコメントがありました。

Just to save someone else the 2 minutes waiting for a bundle update sprockets that will fail, beta.2 is required by rails 3.1.0beta1. You want gem ‘sprockets’, ‘2.0.0.beta.2’ in your Gemfile. github https://github.com/rails/rails/issues/453

のようでGemfileに下記を追記し再度bundle update。

gem 'sprockets', '2.0.0.beta.2'

解決〜

rails server running

全文: http://iain.nl/2011/01/cucumber-vs-steak

Also, the natural language is closer to your understanding of the problem you’re trying to solve. When I write in code, my programmer side becomes active. My programmer side is focussed on solutions. But I want to delay the solution as long as I can, until we have a decent understanding of the problem. So by not writing in code, you can focus more on the problem, rather than on the solution.

ここの「ソリューションをディレー」するところに共感しました。 Cucumberでは自然言語で書けるため、実装から離れた視点でいろんな「Problem」にぶつかりやすい!というのが最もの魅力ですね。 時には本当に実装から離れてプロデューサの目でやりたいことをを考えたいです。そうできないと、いつも「ソリューション」だけに力入れて考えて、もっと重要な「目的」を失うかもしれませんと思います。 もしSteakのような実装の観点から書いたテストコードだとnullとかblankとか、書いてるうちに視野がどんどん狭くなりがちかなと。もちろんそういうテストも重要ですが、「そもそもこんな仕様で大丈夫?ここで何をすべきか?」のような問題にぶつかるためには、やはりCucumberのような自然言語が有利ですね。

あ~いつRoRの仕事ができるかなー

#rails #ruby #mac #環境構築

MacにはデフォルトでRubyが入ってそうです。 ターミナルを開いてrails -vを叩いたらバージョン情報が出てきました。

ruby 1.8.7 (2009-06-08 patchlevel 173) *universal-darwin10.0*

そしてRubyだけじゃなくRailsも入ってましてびっくりしました。 すごいですねMacは。。。 て、railsのバージョンもrails -vで確認できますが、 デフォルトのバージョンは古いそうで下記のコマンドでアップグレードできます。

sudo gem update rails

するとこんなログ情報が出ます。

Updating installed gems
Updating rails
WARNING:  Installing to ~/.gem since /Library/Ruby/Gems/1.8 and
	  /usr/bin aren't both writable.
WARNING:  You don't have /Users/zolo/.gem/ruby/1.8/bin in your PATH,
	  gem executables will not run.
Successfully installed activesupport-2.3.8
Successfully installed activerecord-2.3.8
Successfully installed rack-1.1.0
Successfully installed actionpack-2.3.8
Successfully installed actionmailer-2.3.8
Successfully installed activeresource-2.3.8
Successfully installed rails-2.3.8
Gems updated: activesupport, activerecord, rack, actionpack, actionmailer, activeresource, rails
Installing ri documentation for activesupport-2.3.8...
Installing ri documentation for activerecord-2.3.8...
Installing ri documentation for rack-1.1.0...
Installing ri documentation for actionpack-2.3.8...
Installing ri documentation for actionmailer-2.3.8...
Installing ri documentation for activeresource-2.3.8...
Installing ri documentation for rails-2.3.8...
Installing RDoc documentation for activesupport-2.3.8...
Installing RDoc documentation for activerecord-2.3.8...
Installing RDoc documentation for rack-1.1.0...
Installing RDoc documentation for actionpack-2.3.8...
Installing RDoc documentation for actionmailer-2.3.8...
Installing RDoc documentation for activeresource-2.3.8...
Installing RDoc documentation for rails-2.3.8...

多少時間がかかります。 これでMacでのRuby開発の準備は完了です。

更新

gem update railsにsudoを付けないとこんなエラーが出るかも

WARNING:  Installing to ~/.gem since /Library/Ruby/Gems/1.8 and
	  /usr/bin aren't both writable.
WARNING:  You don't have /Users/paku-k/.gem/ruby/1.8/bin in your PATH,
	  gem executables will not run.
ERROR:  Error installing rails:
	bundler requires RubyGems version >= 1.3.6
#diary #linux #ruby #new

終電検索

いつもYahooで終電を検索するんですが、それがアテにならないことが分かりました。 終電検索で深夜1時とか出発でただ乗換が多かったのを見てとりあえず帰れるって安心したんですが、あとで見ると実は二日目の朝4~5時の電車となってしまいました。時間を全部チェックしてなかったのが自分のミスでしたが、、、検索アルゴリズムを改善する必要があると思います。

ブレスト

ブレインストーミングのこと。

ブレインストーミング(Brainstorming)とはアレックス・F・オズボーンによって考案された会議方式のひとつ。集団思考とも訳される。集団発想法、ブレインストーミング法(BS法)、ブレスト、課題抽出ともいう。1941年に良いアイデアを生み出す状態の解析が行われた後、1953年に発行した著書「Applied Imagination」の中で会議方式の名称として使用された。

rsync

rsync is a file transfer program for Unix systems. rsync uses the “rsync algorithm” which provides a very fast method for bringing remote files into sync. It does this by sending just the differences in the files across the link, without requiring that both sets of files are present at one of the ends of the link beforehand.

Some features of rsync include

  • can update whole directory trees and filesystems
  • optionally preserves symbolic links, hard links, file ownership, permissions, devices and times
  • requires no special privileges to install
  • internal pipelining reduces latency for multiple files
  • can use rsh, ssh or direct sockets as the transport
  • supports anonymous rsync which is ideal for mirroring

http://www.samba.org/rsync/

cron

Cron is a time-based job scheduler in Unix-like computer operating systems. The name cron comes from the word “chronos”, Greek for “time”. Cron enables users to schedule jobs (commands or shell scripts) to run periodically at certain times or dates. It is commonly used to automate system maintenance or administration, though its general-purpose nature means that it can be used for other purposes, such as connecting to the Internet and downloading email.

http://en.wikipedia.org/wiki/Cron

redcar

結構使えそう。

  • Cross platform: OS X, Linux, Windows.
  • Syntax highlighting for many languages
  • Snippets for many languages
  • TextMate Theme support
  • Split panes
  • Block typing
  • Soft tabs
  • Optional line numbers
  • Bracket and quote matching
  • Automatic indentation for many languages
  • Directory tree pane (not yet a full project view)
  • Extend with Ruby
  • My Plugin – example plugin to start playing with editing for yourself
  • Bulk Rename files and directories
  • Source Control integration for Subversion and Git
  • Build System support via Runnables

http://redcareditor.com/

#linux #rails #ruby #sqlite

経緯

何も考えずにGemfileにsqlite3を定義してbundleを流したらこんなエラーが出ました。

$ gem install sqlite3-ruby
Building native extensions.  This could take a while...
ERROR:  Error installing sqlite3-ruby:
        ERROR: Failed to build gem native extension.

/home/user/.rvm/rubies/ruby-head/bin/ruby extconf.rb
checking for sqlite3.h... no
sqlite3.h is missing. Try 'port install sqlite3 +universal' or 'yum install sqlite3-devel'
###  extconf.rb failed ###
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=/home/user/.rvm/rubies/ruby-head/bin/ruby
        --with-sqlite3-dir
        --without-sqlite3-dir
        --with-sqlite3-include
        --without-sqlite3-include=${sqlite3-dir}/include
        --with-sqlite3-lib
        --without-sqlite3-lib=${sqlite3-dir}/lib


Gem files will remain installed in /home/user/.rvm/gems/ruby-head/gems/sqlite3-ruby-1.3.0 for inspection.
Results logged to /home/user/.rvm/gems/ruby-head/gems/sqlite3-ruby-1.3.0/ext/sqlite3/gem_make.out

キーのメッセージは「sqlite3.h is missing. Try ‘port install sqlite3 +universal’ or ‘yum install sqlite3-devel’」なのでそのとおりコマンドを流しましたが、portはそのコマンドがないと、yumはsqlite3-develを見つからないと返事したんです。。。

なのでsqlite本家でソースをダウンロードしビルドしてインストールする必要があります。

sqlite3のインストール

http://www.sqlite.org/download.htmlからsqlite-amalgamation-x.x.x.tar.gz(この記事を書いてる時点では3.7.3)のTarballバージョンのファイルをダウンロードします。上から二番目のリンクです。

$ wget http://www.sqlite.org/sqlite-amalgamation-3.7.3.tar.gz
$ tar vxzf sqlite-amalgamation-3.7.3.tar.gz
$ cd sqlite-amalgamation-3.7.3
$ ./configure --prefix=/usr/local
$ make
$ sudo make install

sqlite-ruby gemのインストール

後は普通にgem installでもいいしbundle installでもOKです。

$ gem install sqlite3-ruby
#ruby

Rubyでは変数の型を宣言しないです。 そのため、オブジェクトは実際に何型かがわからない時が多いです。 オブジェクトのクラスを調べるには以下の三つの方法があります。

class

オブジェクトのクラスを調べられます。 返された結果はクラス名です。 例:

"文字列です。".class

出力結果:string

kind_of?

オブジェクトは特定のクラス又はそのサブクラスのインスタンスかどうかを調べられます。 モジュールに関しても、調べられます。 返された結果はtrue又はflaseです。 例:

"文字列です。".kind_of?(String)

出力結果:true

ちなみに、is_a?メソッドもあります。kind_of?の使い方と同じです。

instance_of?

オブジェクトは特定のクラスのインスタンスかどうかを調べられます。 kind_of?との区別は、サブクラスを含まらないことです。 つまり、kind_of?はサブクラスまで調べられますが、 instance_of?は特定のクラスだけ、サブクラスを調べられないです。 返された結果はtrue又はflaseです。 例:

"文字列です。".instance_of?(String)

出力結果:true

#ruby

ブロックとは?

Rubyでは、メソッドにデータを渡すだけではなく、処理も渡せます。 メソッドに渡された処理はブロックといいます。

ブロックを渡すには?

ブロックを渡すには、二つの方法があります。

  • ①メソッドの最後に{}で囲んだコードを渡す。
test_block {puts 'In the block'}
  • ②メソッドの最後にdo..endで囲んだコードを渡す。
test_block do
  puts 'In the block'
end

ブロックの使い方?

ブロックは使ってもらわないと、意味がありません。 使ってもらうということは、相手のメソッドが、ブロックの処理を実行することです。 メソッドの中で、渡されたブロックの処理を実行するには、yieldを使います。

def test_block
  # test_blockメソッドを定義する
  puts 'Start of method'
  yield
  puts 'End of method'
end

test_block {puts 'In the block'}

実行結果:

Start of method
In the block
End of method

ブロックにはパラメータを渡す?

ブロックにはパラメータを渡せますか?もちろんです。 パラメータの定義はブロックで、 yieldでブロックを実行する際には、パラメータを渡します。 ブロックは渡されたパラメータを受け取って、処理します。 文字の説明だけで、わからないかもしれません。 実はメソッドの定義とほとんど変わらないです。 サンプルを見てみましょう。

def test_block_pramater
  yield('helloworld')
end
call_block {|str, num| puts 'Ruby sample:'+str }

※注意点:ブロックでは、||でパラメータを受け取っています。

渡されたブロックをさらに別のメソッドを渡すには?

渡されたブロックをさらに内部で使っているメソッドに渡すことができます。 引数の最後に&付きの引数を指定してブロックを受け取リます。

def test_block(&block)
  # test_blockメソッドを定義する
  puts 'Start of test_block'
  test_block_paramater(&block)
  puts 'End of test_block'
end

def test_block_paramater(&block)
  puts 'Start of test_block_paramater'
  yield
  puts'End of test_block_paramater'
end

test_block {puts 'In the block'}

実行結果:

Start of test_block
Start of test_block_paramater
In the block
End of test_block_paramater
End of test_block

※One Point:ブロック引数を渡す時、&がつければ、引数名は何でも大丈夫です。

ブロックが渡されたか調べるには?

yieldを実行する時、ブロックが渡されるかどうかを確認することができます。 block_given?を使って、ブロックがあるかどうかを確認できます。

def test_block
  # test_blockメソッドを定義する
  puts 'Start of method'
  yield if block_given?
  puts 'End of method'
end

test_block {puts 'In the block'}