Posts Tagged ‘Ruby’

, | No Comments | 5月 20th, 2009

RailsのActiveRecordで、save! とかすると保存に失敗したとき例外を投げてくれる。例えば、User.create!(params[:user]) とかして、失敗すると、ActiveRecord::RecordInvalid を投げてくれるのだけど、エラーをどうやって取るのか調べたのでメモ。

よくある例で、ユーザが作れたら index へ遷移して、作れなかったら new で再入力させるという場合。

createを使う場合

def create
  if @user = User.create(params[:user])
    flash[:notice] = 'ユーザ作成しました'
    redirect_to :action => 'index'
  else
    # ここでは、@user.errors でエラーが取れる
    render :action => 'new'
  end
end

create!を使う場合

def create
  @user = User.create!(params[:user])
  flash[:notice] = 'ユーザ作成しました'
  redirect_to :action => 'index'
rescue ActiveRecord::RecordInvalid => e
  # @user は nil になっているので、 @user.errors でエラーが取れない。
  render :action => 'new'
end

としたとき、create! で例外が飛んでいるので、当然 @user は nil となってます。なので、rescue 句の中で @user.errors ではエラーが取れません。

調べたところ、e.record で、ActiveRecord の例外を発生させたインスタンスが取れるようです。

def create
  @user = User.create!(params[:user])
  flash[:notice] = 'ユーザ作成しました'
  redirect_to :action => 'index'
rescue ActiveRecord::RecordInvalid => e
  # e.record に Userクラスのインスタンスが入ってる。
  @user = e.record
  render :action => 'new'
end

たとえば、View内で

< %= error_messages_for :user %>

とかしたい場合は、@user = e.record として置けばエラーが楽に表示出来て良い。

| No Comments | 5月 12th, 2009

OSXを使って、rubyでtokyotyrant使ってみた。

インストール

tokyocabinet

最新版を公式サイトから落としてくる。現時点での最新は、1.4.20だった。

% curl -O http://tokyocabinet.sourceforge.net/tokyocabinet-1.4.20.tar.gz
% tar xvzf tokyocabinet-1.4.20.tar.gz
% cd tokyocabinet-1.4.20
% ./confiruge --prefix=/usr/local
% make 
# make install
tokyotyrant

同様に、最新版を公式サイトのtokyotyrantのパッケージ一覧から落としてくる。現時点での最新は、1.1.26だった。

% curl -O http://tokyocabinet.sourceforge.net/tyrantpkg/tokyotyrant-1.1.26.tar.gz
% tar xvzf tokyotyrant-1.1.26.tar.gz
% cd tokyotyrant-1.1.26
% ./confiruge --prefix=/usr/local
% make 
# make install
tokyocabinet Ruby用API

同様に、最新版を公式サイトのRubyAPIの一覧から落としてくる。現時点での最新は、1.23だった。

% curl -O http://tokyocabinet.sourceforge.net/rubypkg/tokyocabinet-ruby-1.23.tar.gz
% tar xvzf tokyocabinet-ruby-1.23.tar.gz
% cd tokyocabinet-ruby-1.23
% ruby extconf.rb
% make 
# make install
tokyotyrant Ruby用API

同様に、最新版を公式サイトのRubyAPIの一覧から落としてくる。現時点での最新は、1.5だった。

% curl -O http://tokyocabinet.sourceforge.net/tyrantrubypkg/tokyotyrant-ruby-1.5.tar.gz
% tar xvzf tokyotyrant-ruby-1.5.tar.gz
% cd cd tokyotyrant-ruby-1.5
# ruby install.rb

tokyotyrantサーバを起動してみる

% sudo /usr/local/sbin/ttservctl start
Starting the server of Tokyo Tyrant
/usr/local/sbin/ttservctl: line 49: ulimit: open files: cannot modify limit: Invalid argument
Executing: ttserver -port 1978 -dmn -pid /var/ttserver/pid
Done

なんかエラーが出るので、/usr/local/sbin/ttservctl の49行目を見てみる。

48
49
50
if [ -n "$maxcon" ] ; then
   ulimit -n "$maxcon"
 fi

maxcon という変数を見てみると

21
22
23
dbname="$basedir/casket.tch#bnum=1000000"
maxcon="65535"
retval=0

ulimit がエラーらしいが、ulimit がよく分からない。適当に数字を maxcon=6000 とかしたらエラー消えたけどいいのか…?

というわけで、無事起動。

接続

シェルから接続する場合は、tcrmgr というコマンドを使うらしい。

値の設定

tcrmgr put {host} {key} {value} という書式でセットする。name というキーに、CHU といれるならば、

tcrmgr set localhost name CHU
値の取得

tcrmgr get {host} {key} という書式でゲットする。name というキーの値を取得するならば、

tcrmgr get localhost name

とりあえず、起動して動いているようだ。

, , | No Comments | 8月 18th, 2008

 よりよい家計簿を目指して、RubyAMFを使ってみる。Rails + Flex3.0 でやろうと。

インストール(Rails側)

$ script/plugin install --force http://rubyamf.googlecode.com/svn/trunk/rubyamf/

設定

 インストールすると config/rubyamf_config.rb が出来るので、ここで設定を行う。

無視したいフィールドがあったら、下記のように指定する。

ClassMappings.ignore_fields = ['created_at','created_on','updated_at','updated_on']

ActionScript側で、変数名をキャメルにするかアンスコ区切りにするか。

ClassMappings.translate_case = false

public var created_at:Date;

ClassMappings.translate_case = true

public var createdAt:Date; // created_at in rails

AS側で、動的にRailのモデルと関連づけを出来るようにするか。ARから派生したモデル以外でも使えるみたい。

ClassMappings.assume_types = true

指定は、以下のようにする。
# Flash:: fl.net.registerClassAlias(‘User’,User)
# Flex:: [RemoteClass(alias='User')]

ClassMappings.assume_types = false のとき、以下のようにしてRails側とAS側のマッピングをするか。

ClassMappings.register(:actionscript => 'Address', :ruby => 'Address', :type => 'active_record')

とすると、
Ruby側

class Address < ActiveRecord::Base

AS側

[RemoteClass(alias="Address")]
public class Address {

デフォルトだと、ASから送られてくる日付は Time オブジェクトになるが、これを DateTime オブジェクトにするかどうか。true で DateTime, false で Time。

ClassMappings.use_ruby_date_time = true

これを true にすると、associationを eager load してくれるみたいです。false にすると、いちいち設定する必要があります。

ClassMappings.check_for_associations = true

AS側で保存したときに、Rails側でどのように受け取るかの設定。

ParameterMappings.scaffolding = false

として、AS側でsaveしたとき

save(context);

Rails側では、以下のように受け取ります。

def save
  @context = params[0]
ParameterMappings.scaffolding = true

として、AS側でsaveしたとき

save(
   {context:context}
);

Rails側では、以下のように受け取ります。

def save
  @context =
     params[:context]

書きかけ。

, , , | 2 Comments | 5月 1st, 2008

まず、ImageMagickのインストールです。jpg,pngを扱うときはlibpng, libjpeg が必要になるのであらかじめインストールしておきます(後から入れても動いた)。

ダウンロード先

libjpegのインストール

Independent JPEG Group のサイトから、jpegsrc.v6b.tar.gz のソースをダウンロードしてきます。コンパイルしたあと、make install-lib とすることで jpeglib がインストールされるようだ。

$ wget http://www.ijg.org/files/jpegsrc.v6b.tar.gz
$ tar xvzf jpegsrc.v6b.tar.gz
$ ./configure --prefix=/usr/local/
$ make
# make install
# make install-lib

これで通らないときは、 *.so のファイルを作る –enable-shared オプションを付けて configure すると通るかも。

./configure --prefix=/usr/local --enable-shared

libpngのインストール

INSTALL には、 configure して make すればおkみたいな感じで書いてあるけど、通らないときがある。libpng インストール を参考にして、予め用意されているmakefile を編集することでインストール出来るようだ。

$ wget http://jaist.dl.sourceforge.net/sourceforge/libpng/libpng-1.2.28.tar.gz
$ tar xvzf libpng-1.2.28.tar.gz
$ cd libpng-1.2.28
$ cp script/makefile.linux makefile
$ vi makefile
 
ZLIBの辺りを以下のように書き換える。
 
ZLIBLIB=/usr/local/lib
ZLIBINC=/usr/local/include
#ZLIBLIB=../zlib
#ZLIBINC=../zlib
 
$ make
# make install

なぜかmakeが1回では通らず、2回makeすると通る。(RedHat ES4で2回起きた)

ImageMagickのインストール

$ wget ftp://ftp.kddlabs.co.jp/graphics/ImageMagick/ImageMagick-6.4.1-0.tar.gz
$ tar xvzf ImageMagick-6.4.0-11.tar.gz
$ cd ImageMagick-6.4.0
$ ./configure --prefix=/usr/local
$ make
$ make test
# make install

make install で

/bin/install: cannot create regular file `/usr/local/man/man1/cjpeg.1': No such file or directory

と出てしまったときは、ディレクトリが出来ていないようなので、以下のコマンドを実行してから再トライしてみれば通るはず。

# install -d /usr/local/man/man1

これやると、libMagick* 系のライブラリがないって言われる… /usr/local/lib/libMagick* を /lib/ 以下にコピーすればいいんだけど、しっくりこないです。

Rmagickのインストール

Rubygemsがインストール済みの上で以下を実行

# gem install rmagick

, | 1 Comment | 4月 20th, 2008

以下のサイトを参考にRailsでQRコード作ってみた。

MacにGDとRubyGDをインストール

$ sudo port install gd2
$ sudo port install rb-gd

QRコードクラスライブラリ for Ruby をDLしてきて、RAILS_ROOT + ‘/lib’ 以下に設置。

このまま使ってみると、qrcode.rb の Regexp.compileでエラーが出るので、 該当の箇所を書き換える。RailsでQRコードを生成を参考にして、Regexp.comple の第3引数でデフォルトエンコードに戻すようです。

# Regexp.compile(n3_search))
# ↓みたいに引数を追加。合計4箇所あるはず。
Regexp.compile(n3_search, false, 'n'))

ReadMeに QrcodeのコンストラクタでQrcode用のデータを @path を設定しているので、これを変更しろとのことで、 @path = RAILS_ROOT + ‘/lib/qrcode_data’ と変更する。これは高速化のために必要と書いてある。

あとは、読み込みたいところで以下のようにして使う。RubyでQRコードを作ろうを参考に以下のような形で。

ruby script/console とか立ち上げると

>>require 'qrcode_img'
>> url = "http://d.hatena.ne.jp/omochist/"
>> qr = Qrcode.new
>> qr_data = qr.make_qrcode(url)
>> qr_image = Qrcode_image.new
>> qr_image.image_out(qr_data, 'png', 'ecpplue.png')

これで、RAILS_ROOT に ecpplus.png っていうQRが出来ています。

QRコードの大きさを変えたいときは、Qrcode_image に @module_size, @quiet_zone というのがあるので、これを調節する。

@module_size # 全体の大きさ
@quiet_zone # 余白

>> qr_image = Qrcode_image.new
>> qr_image.set_module_size(7)  # 1-8が指定可能なようだ
>> qr_image.set_quiet_zone(1)  # 1-8が指定可能なようだ

あとはさっきと同じような感じ。

download the hurt locker