module ActiveModel::Serialization
def serializable_add_includes(options = {}) #:nodoc:
+opts+ - options for the association records
+records+ - the association record(s) to be serialized
+association+ - name of the association
Expects a block that takes as arguments:
Add associations specified via the :include option.
def serializable_add_includes(options = {}) #:nodoc: return unless includes = options[:include] unless includes.is_a?(Hash) includes = Hash[Array(includes).map { |n| n.is_a?(Hash) ? n.to_a.first : [n, {}] }] end includes.each do |association, opts| if records = send(association) yield association, records, opts end end end
def serializable_hash(options = nil)
user.serializable_hash(include: { notes: { only: 'title' }})
# => {"name" => "Napoleon"}
user.serializable_hash
user.notes = [note]
user.name = 'Napoleon'
user = User.new
note.text = 'Some text here'
note.title = 'Battle of Austerlitz'
note = Note.new
end
end
{'title' => nil, 'text' => nil}
def attributes
attr_accessor :title, :text
include ActiveModel::Serializers::JSON
class Note
end
end
{'name' => nil}
def attributes
attr_accessor :name, :notes # Emulate has_many :notes
include ActiveModel::Serializers::JSON
class User
Example with :include option
# => {"name"=>"bob", "age"=>22, "capitalized_name"=>"Bob"}
person.serializable_hash(methods: :capitalized_name)
person.serializable_hash(except: :name) # => {"age"=>22}
person.serializable_hash(only: :name) # => {"name"=>"bob"}
person.serializable_hash # => {"name"=>"bob", "age"=>22}
person.age = 22
person.name = 'bob'
person = Person.new
end
end
name.capitalize
def capitalized_name
end
{'name' => nil, 'age' => nil}
def attributes
attr_accessor :name, :age
include ActiveModel::Serialization
class Person
Returns a serialized hash of your object.
def serializable_hash(options = nil) options ||= {} attribute_names = attributes.keys if only = options[:only] attribute_names &= Array(only).map(&:to_s) elsif except = options[:except] attribute_names -= Array(except).map(&:to_s) end hash = {} attribute_names.each { |n| hash[n] = read_attribute_for_serialization(n) } Array(options[:methods]).each { |m| hash[m.to_s] = send(m) } serializable_add_includes(options) do |association, records, opts| hash[association.to_s] = if records.respond_to?(:to_ary) records.to_ary.map { |a| a.serializable_hash(opts) } else records.serializable_hash(opts) end end hash end