2009-07-21 05:51:57 +00:00
|
|
|
module ActiveModel
|
2010-06-14 08:58:00 +00:00
|
|
|
# == Active Model Conversions
|
|
|
|
#
|
|
|
|
# Handles default conversions: to_model, to_key and to_param.
|
2010-02-21 07:47:37 +00:00
|
|
|
#
|
|
|
|
# == Example
|
|
|
|
#
|
|
|
|
# Let's take for example this non persisted object.
|
|
|
|
#
|
|
|
|
# class ContactMessage
|
2010-01-16 21:56:20 +00:00
|
|
|
# include ActiveModel::Conversion
|
2010-02-21 07:47:37 +00:00
|
|
|
#
|
2010-02-21 10:09:21 +00:00
|
|
|
# # ContactMessage are never persisted in the DB
|
|
|
|
# def persisted?
|
|
|
|
# false
|
2010-02-21 07:47:37 +00:00
|
|
|
# end
|
2010-01-16 21:56:20 +00:00
|
|
|
# end
|
2010-02-21 07:47:37 +00:00
|
|
|
#
|
|
|
|
# cm = ContactMessage.new
|
2010-07-30 00:30:04 +00:00
|
|
|
# cm.to_model == self # => true
|
|
|
|
# cm.to_key # => nil
|
|
|
|
# cm.to_param # => nil
|
2010-02-21 07:47:37 +00:00
|
|
|
#
|
2009-07-21 05:51:57 +00:00
|
|
|
module Conversion
|
2010-08-14 05:13:00 +00: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 08:58:00 +00:00
|
|
|
# self.
|
2010-08-14 05:13:00 +00: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 08:58:00 +00:00
|
|
|
# your object with Active Model compliant methods.
|
2009-07-21 05:51:57 +00:00
|
|
|
def to_model
|
|
|
|
self
|
|
|
|
end
|
2010-02-21 07:47:37 +00:00
|
|
|
|
2010-08-15 14:29:15 +00: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 07:47:37 +00:00
|
|
|
def to_key
|
2010-02-21 10:09:21 +00:00
|
|
|
persisted? ? [id] : nil
|
2010-02-21 07:47:37 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
# Returns a string representing the object's key suitable for use in URLs,
|
2010-02-21 10:09:21 +00:00
|
|
|
# or nil if persisted? is false
|
2010-02-21 07:47:37 +00:00
|
|
|
def to_param
|
2010-08-15 14:29:15 +00:00
|
|
|
persisted? ? to_key.join('-') : nil
|
2010-02-21 07:47:37 +00:00
|
|
|
end
|
2009-07-21 05:51:57 +00:00
|
|
|
end
|
|
|
|
end
|