serialization.rb 2.5 KB
Newer Older
1 2 3 4
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/hash/slice'

module ActiveModel
R
Rizwan Reza 已提交
5
  # == Active Model Serialization
6
  #
7
  # Provides a basic serialization to a serializable_hash for your object.
8
  #
9
  # A minimal implementation could be:
10
  #
11
  #   class Person
12
  #
13
  #     include ActiveModel::Serialization
14
  #
15
  #     attr_accessor :name
16
  #
17
  #     def attributes
18
  #       {'name' => name}
19
  #     end
20
  #
21
  #   end
22
  #
23
  # Which would provide you with:
24
  #
25 26 27 28 29 30 31
  #   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.
32 33
  #
  # Most of the time though, you will want to include the JSON or XML
34
  # serializations. Both of these modules automatically include the
35 36
  # ActiveModel::Serialization module, so there is no need to explicitly
  # include it.
37
  #
38
  # So a minimal implementation including XML and JSON would be:
39
  #
40
  #   class Person
41
  #
42 43
  #     include ActiveModel::Serializers::JSON
  #     include ActiveModel::Serializers::Xml
44
  #
45
  #     attr_accessor :name
46
  #
47
  #     def attributes
48
  #       {'name' => name}
49
  #     end
50
  #
51
  #   end
52
  #
53
  # Which would provide you with:
54
  #
55 56
  #   person = Person.new
  #   person.serializable_hash   # => {"name"=>nil}
57 58
  #   person.as_json             # => {"name"=>nil}
  #   person.to_json             # => "{\"name\":null}"
59
  #   person.to_xml              # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
60
  #
61 62
  #   person.name = "Bob"
  #   person.serializable_hash   # => {"name"=>"Bob"}
63 64
  #   person.as_json             # => {"name"=>"Bob"}
  #   person.to_json             # => "{\"name\":\"Bob\"}"
65
  #   person.to_xml              # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
66
  #
67
  # Valid options are <tt>:only</tt>, <tt>:except</tt> and <tt>:methods</tt> .
68 69 70 71 72
  module Serialization
    def serializable_hash(options = nil)
      options ||= {}

      attribute_names = attributes.keys.sort
73 74 75 76
      if only = options[:only]
        attribute_names &= Array.wrap(only).map(&:to_s)
      elsif except = options[:except]
        attribute_names -= Array.wrap(except).map(&:to_s)
77 78
      end

J
John Firebaugh 已提交
79
      method_names = Array.wrap(options[:methods]).select { |n| respond_to?(n) }
80
      Hash[(attribute_names + method_names).map { |n| [n, send(n)] }]
81 82 83
    end
  end
end