Rails4になってから、ActiveModelというAPIもすげシンプルになった。

http://tsubo3.wordpress.com/2011/12/26/rails3-activerecordではないモデル/
上のブログに書かれているコードをRails4にすると以下になると思います。

元のRails3のコード:
app/models/contact.rb



class Contact
include ActiveModel::Conversion
include ActiveModel::Validations
extend ActiveModel::Naming
extend ActiveModel::Translation

attr_accessor :name
attr_accessor :email
attr_accessor :subject
attr_accessor :message

validates :name, :presence => true
validates :email, :presence => true,
:confirmation => true,
:format => { :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i }
validates :subject, :presence => true
validates :message, :presence => true

def persisted?; false; end

def initialize(attributes = {})
self.attributes = attributes
end

def attributes=(attributes = {})
if attributes
attributes.each do |name, value|
send "#{name}=", value
end
end
end

def attributes
Hash[instance_variable_names.map{|v| [v[1..-1], instance_variable_get(v)]}]
end
end

Rails4にすると



class Contact
include ActiveModel::Model
attr_accessor :name, :email, :subject, :message

validates :name, :presence => true
validates :email, :presence => true,
:confirmation => true,
:format => { :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i }
validates :subject, :presence => true
validates :message, :presence => true
end

include ActiveModel::Modelを追加しただけで すごくシンプルになるね。