トップ «前の日記(2010-01-21) 最新 次の日記(2010-01-27)» 編集

Ussy Diary


2010-01-23

Encoding::UndefinedConversionError

Ruby 1.9 上の Sequel で sqlite3 からマルチバイト文字列を含んだレコードを取得し to_json しようとすると

Encoding::UndefinedConversionError: "\xE2" from ASCII-8BIT to UTF-8

というエラーが出力されます。

String#force_encoding で、いちいち utf-8 しないといけないのかと思ったところ、きちんと Sequel の plugin にエンコーディングを変換できるものが提供されていました。

class User < Sequel::Model
  plugin :force_encoding, 'utf-8'
end
Tags: Ruby Sequel

Sequel で保存時にタイムスタンプをつける

カラム名を created_at, updated_at にしておくと、 save メソッドを呼び出したときに自動的に作成、更新時間を更新してくれるみたいです。カラム型は timestamp で確認しています。

さらに追加時にも更新時間を入れたい場合には timestamps プラグインを利用して、オプションを渡してあげるとよいです。

DB = Sequel.connect("sqlite://test.db")

class User < Sequel::Model
  plugin :timestamps, :update_on_create => true
end

DB.transaction do
  User.new(:name => 'aaa').save
  User.new(:name => 'bbb').save
end

既存システムで、すでに別のカラム名が使われている場合には下のオプションを渡してあげると変更できます。

plugin :timestamps, :create => 'created_on', :update => 'updated_on'

Module: Sequel::Plugins::Timestamps [Sequel: The Database Toolkit for Ruby]

モデルすべてに適用したい場合は Sequel::Model で定義してあげるとよいみたいです。

class Sequel::Model
   plugin :timestamps, :update_on_create => true, :create => 'created_on', :update => 'updated_on'
end

class User < Sequel::Model; end
Tags: Ruby Sequel