ActiveModel:让Ruby对象拥有ActiveRecord的行为[转]

Ruby on Rails的核心成员,Yehuda Katz在其博客中介绍了ActiveModel,Rails 3中的另一个重要功能。ActiveModel是一个新的库,提供ActiveRecord的部分model,但不受数据库限制。

通过使用ActiveModel,任何Ruby类都能拥有类似Rails的model行为,而且不会受到Rails和数据库的限制,以下是在非Rails类上使用 ActiveModel的一个示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
require 'active_model'
 
class Person
  include ActiveModel::Validations
 
  validates_presence_of :first_name, :last_name
 
  attr_accessor :first_name, :last_name
  def initialize(first_name, last_name)
    @first_name, @last_name = first_name, last_name
  end
end
 
a = Person.new("Fred", nil)
a.valid? # => false
a.last_name = "Flintstone"
a.valid? # => true

原文地址
http://www.javaeye.com/news/12993

Monitor Your Web Site 24/7 - Receive email and SMS alerts anytime your web site goes down.

Related Posts

Leave a Reply

Monitor Your Web Site 24/7 - Receive email and SMS alerts anytime your web site goes down.

About Me

About Me
Record Technical Articles at Gooss.org.

Entries (RSS) and Comments (RSS). Valid XHTML and CSS and XFN.

© Copyright 2009 山海经. All rights reserved.

Social Bookmarks

Copyright © Designed by: Free WP Templates
Food Charts |  About Breast Milk |  Organic Food