Provides a basic serialization to a serializable_hash for your object.
A minimal implementation could be:
class Person
include ActiveModel::Serialization
attr_accessor :name
def attributes
@attributes ||= {'name' => 'nil'}
end
end
Which would provide you with:
person = Person.new
person.serializable_hash # => {"name"=>nil}
person.name = "Bob"
person.serializable_hash # => {"name"=>"Bob"}
You need to declare some sort of attributes hash which contains the attributes you want to serialize and their current value.
Most of the time though, you will want to include the JSON or XML serializations. Both of these modules automatically include the ActiveModel::Serialization module, so there is no need to explicitly include it.
So a minimal implementation including XML and JSON would be:
class Person
include ActiveModel::Serializers::JSON
include ActiveModel::Serializers::Xml
attr_accessor :name
def attributes
@attributes ||= {'name' => 'nil'}
end
end
Which would provide you with:
person = Person.new
person.serializable_hash # => {"name"=>nil}
person.to_json # => "{\"name\":null}"
person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
person.name = "Bob"
person.serializable_hash # => {"name"=>"Bob"}
person.to_json # => "{\"name\":\"Bob\"}"
person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
Valid options are :only, :except and :methods .
# File lib/active_model/serialization.rb, line 67
67: def serializable_hash(options = nil)
68: options ||= {}
69:
70: options[:only] = Array.wrap(options[:only]).map { |n| n.to_s }
71: options[:except] = Array.wrap(options[:except]).map { |n| n.to_s }
72:
73: attribute_names = attributes.keys.sort
74: if options[:only].any?
75: attribute_names &= options[:only]
76: elsif options[:except].any?
77: attribute_names -= options[:except]
78: end
79:
80: method_names = Array.wrap(options[:methods]).inject([]) do |methods, name|
81: methods << name if respond_to?(name.to_s)
82: methods
83: end
84:
85: (attribute_names + method_names).inject({}) { |hash, name|
86: hash[name] = send(name)
87: hash
88: }
89: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.