model.rb 2.2 KB
Newer Older
1
module ActiveModel
2 3 4

  # == Active Model Basic Model
  #
M
Michael de Silva 已提交
5 6
  # Includes the required interface for an object to interact with <tt>ActionPack</tt>,
  # using different <tt>ActiveModel</tt> modules. It includes model name introspections,
7
  # conversions, translations and validations. Besides that, it allows you to
8
  # initialize the object with a hash of attributes, pretty much like
M
Michael de Silva 已提交
9
  # <tt>ActiveRecord</tt> does.
10 11 12 13 14 15 16 17 18 19 20 21
  #
  # A minimal implementation could be:
  #
  #   class Person
  #     include ActiveModel::Model
  #     attr_accessor :name, :age
  #   end
  #
  #   person = Person.new(:name => 'bob', :age => '18')
  #   person.name # => 'bob'
  #   person.age # => 18
  #
M
Michael de Silva 已提交
22 23
  # Note that, by default, <tt>ActiveModel::Model</tt> implements <tt>persisted?</tt> to
  # return <tt>false</tt>, which is the most common case. You may want to override it
24 25 26 27 28 29 30 31 32 33 34 35 36 37
  # in your class to simulate a different scenario:
  #
  #   class Person
  #     include ActiveModel::Model
  #     attr_accessor :id, :name
  #
  #     def persisted?
  #       self.id == 1
  #     end
  #   end
  #
  #   person = Person.new(:id => 1, :name => 'bob')
  #   person.persisted? # => true
  #
M
Michael de Silva 已提交
38
  # Also, if for some reason you need to run code on <tt>initialize</tt>, make sure you
39 40 41 42 43 44
  # call super if you want the attributes hash initialization to happen.
  #
  #   class Person
  #     include ActiveModel::Model
  #     attr_accessor :id, :name, :omg
  #
O
Oscar Del Ben 已提交
45
  #     def initialize(attributes={})
46 47 48 49 50 51 52 53
  #       super
  #       @omg ||= true
  #     end
  #   end
  #
  #   person = Person.new(:id => 1, :name => 'bob')
  #   person.omg # => true
  #
54
  # For more detailed information on other functionalities available, please refer
M
Michael de Silva 已提交
55
  # to the specific modules included in <tt>ActiveModel::Model</tt> (see below).
56
  module Model
57
    def self.included(base) #:nodoc:
58 59 60 61 62 63 64 65 66 67
      base.class_eval do
        extend  ActiveModel::Naming
        extend  ActiveModel::Translation
        include ActiveModel::Validations
        include ActiveModel::Conversion
      end
    end

    def initialize(params={})
      params.each do |attr, value|
68
        self.public_send("#{attr}=", value)
69 70 71 72 73 74 75 76
      end if params
    end

    def persisted?
      false
    end
  end
end