2009-07-21 01:51:57 -04:00
|
|
|
module ActiveModel
|
2010-06-14 04:58:00 -04:00
|
|
|
# == Active Model Conversions
|
|
|
|
#
|
|
|
|
# Handles default conversions: to_model, to_key and to_param.
|
2010-02-21 02:47:37 -05:00
|
|
|
#
|
|
|
|
# == Example
|
|
|
|
#
|
|
|
|
# Let's take for example this non persisted object.
|
|
|
|
#
|
|
|
|
# class ContactMessage
|
2010-01-16 16:56:20 -05:00
|
|
|
# include ActiveModel::Conversion
|
2010-02-21 02:47:37 -05:00
|
|
|
#
|
2010-02-21 05:09:21 -05:00
|
|
|
# # ContactMessage are never persisted in the DB
|
|
|
|
# def persisted?
|
|
|
|
# false
|
2010-02-21 02:47:37 -05:00
|
|
|
# end
|
2010-01-16 16:56:20 -05:00
|
|
|
# end
|
2010-02-21 02:47:37 -05:00
|
|
|
#
|
|
|
|
# cm = ContactMessage.new
|
2010-07-29 20:30:04 -04:00
|
|
|
# cm.to_model == self # => true
|
|
|
|
# cm.to_key # => nil
|
|
|
|
# cm.to_param # => nil
|
2010-02-21 02:47:37 -05:00
|
|
|
#
|
2009-07-21 01:51:57 -04:00
|
|
|
module Conversion
|
2010-08-14 01:13:00 -04:00
|
|
|
# If your object is already designed to implement all of the Active Model
|
|
|
|
# you can use the default to_model implementation, which simply returns
|
2010-06-14 04:58:00 -04:00
|
|
|
# self.
|
2010-08-14 01:13:00 -04:00
|
|
|
#
|
|
|
|
# If your model does not act like an Active Model object, then you should
|
|
|
|
# define <tt>:to_model</tt> yourself returning a proxy object that wraps
|
2010-06-14 04:58:00 -04:00
|
|
|
# your object with Active Model compliant methods.
|
2009-07-21 01:51:57 -04:00
|
|
|
def to_model
|
|
|
|
self
|
|
|
|
end
|
2010-02-21 02:47:37 -05:00
|
|
|
|
2010-08-15 10:29:15 -04:00
|
|
|
# Returns an Enumerable of all key attributes if any is set, regardless
|
|
|
|
# if the object is persisted or not.
|
|
|
|
#
|
|
|
|
# Note the default implementation uses persisted? just because all objects
|
|
|
|
# in Ruby 1.8.x responds to :id.
|
2010-02-21 02:47:37 -05:00
|
|
|
def to_key
|
2010-02-21 05:09:21 -05:00
|
|
|
persisted? ? [id] : nil
|
2010-02-21 02:47:37 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
# Returns a string representing the object's key suitable for use in URLs,
|
2010-02-21 05:09:21 -05:00
|
|
|
# or nil if persisted? is false
|
2010-02-21 02:47:37 -05:00
|
|
|
def to_param
|
2010-08-15 10:29:15 -04:00
|
|
|
persisted? ? to_key.join('-') : nil
|
2010-02-21 02:47:37 -05:00
|
|
|
end
|
2009-07-21 01:51:57 -04:00
|
|
|
end
|
|
|
|
end
|