Non-Rails app
require 'active_model'
class Support
include ActiveModel::Validations
validates_presence_of :email, :sender_name, :support_type, :content
attr_accessor :email, :sender_name, :support_type, :content
def initialize(attributes = {})
attributes.each do |key, value|
self.send("#{key}=", value)
end
@attributes = attributes
end
def read_attribute_for_validation(key)
@attributes[key]
end
end
s = Support.new(:sender_name => "aji", :support_type => "bug", :content => "OMG!")
s.valid? #=> false
s = Support.new(:email => '[email protected]', :sender_name => "aji", :support_type => "bug", :content => "OMG!")
s.valid? #=> true
s.email = '[email protected]'
s.valid? #=> true
Rails App# app/models/support.rb
class Support
include ActiveModel::Validations
validates_presence_of :email, :sender_name, :support_type, :content
attr_accessor :email, :sender_name, :support_type, :content
def initialize(attributes = {})
attributes.each do |key, value|
self.send("#{key}=", value)
end
@attributes = attributes
end
def read_attribute_for_validation(key)
@attributes[key]
end
end
Selain module ActiveModel::Validations, terdapat module-module lain yang terdapat dari Active Model, yaitu:1. ActiveModel::Serialization = serialization untuk JSON dan XML, yang memungkinkan untuk melakukan: @person.to_json(:except => :comment).
2. ActiveModel::AttributeMethods = Mempermudah untuk menambahkan attribute seperti table_name :my_foo
3. ActiveModel::Callbacks = ActiveRecord-style lifecycle callbacks. Misal, before_create, after_save, dan lain-lain
4. ActiveModel::Dirty = Untuk melakukan dirty tracking
5. ActiveModel::Naming = Implementasi defaul dari model.model_name, dimana digunakan oleh ActionPack. Misal ketika melakukan render :partial => model
6. ActiveModel::Observing = ActiveRecord-style observers
7. ActiveModel::StateMachine = Implementasi sederhana state-machine untuk model
8. ActiveModel::Translation = Core translation support
Lebih lanjut:
1. Rails 3.0’s ActiveModel: How To Give Ruby Classes Some ActiveRecord Magic
2. ActiveModel: Make Any Ruby Object Feel Like ActiveRecord
No comments:
Post a Comment