aboutsummaryrefslogtreecommitdiffstats
path: root/railties/guides/source/active_model_basics.textile
blob: 92fa5bc8f4a33da3309f7f52acedd59ae3012c8f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
h2. Active Model Basics

This guide should provide you with all you need to get started using model classes. Active Model allow for Action Pack helpers to interact with non-ActiveRecord models. Active Model also helps building custom ORMs for use outside of the Rails framework.

endprologue.

WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails.

h3. Introduction

Active Model is a library containing various modules used in developing frameworks that need to interact with the Rails Action Pack library. Active Model provides a known set of interfaces for usage in classes. Some of modules are explained below -  

h4. AttributeMethods

AttributeMethods module can add custom prefixes and suffixes on methods of a class. It is used by defining the prefixes and suffixes, which methods on the object will use them.

<ruby>
class Person
  include ActiveModel::AttributeMethods

  attribute_method_prefix 'reset_'
  attribute_method_suffix '_highest?'
  define_attribute_methods ['age']

  attr_accessor :age

private
  def reset_attribute(attribute)
    send("#{attribute}=", 0)
  end

  def attribute_highest?(attribute)
    send(attribute) > 100 ? true : false
  end
  
end

person = Person.new
person.age = 110
person.age_highest?  # true
person.reset_age     # 0
person.age_highest?  # false 

</ruby>

h4. Callbacks

Callbacks gives Active Record style callbacks. This provides the ability to define the callbacks and those will run at appropriate time. After defining a callbacks you can wrap with before, after and around custom methods.

<ruby>
class Person
  extend ActiveModel::Callbacks

  define_model_callbacks :update

  before_update :reset_me

  def update
    _run_update_callbacks do
      # This will call when we are trying to call update on object.
    end
  end

  def reset_me
    # This method will call when you are calling update on object as a before_update callback as defined.
  end
end
</ruby>

h3. Changelog

* August 5, 2011: Initial version by "Arun Agrawal":http://github.com/arunagw