Module: MongoModel::Serialization

Extended by:
ActiveSupport::Concern
Includes:
ActiveModel::Serializers::JSON
Included in:
EmbeddedDocument
Defined in:
lib/mongomodel/concerns/serialization.rb

Instance Method Summary collapse

Instance Method Details

#serializable_hash(given_options = nil) ⇒ Object


7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/mongomodel/concerns/serialization.rb', line 7

def serializable_hash(given_options = nil)
  options = given_options ? given_options.dup : {}

  options[:only]    = Array.wrap(options[:only]).map { |n| n.to_s }
  options[:except]  = Array.wrap(options[:except]).map { |n| n.to_s }
  options[:methods] = Array.wrap(options[:methods]).map { |n| n.to_s }

  attribute_names = attributes_for_serialization

  if options[:only].any?
    attribute_names &= options[:only]
  elsif options[:except].any?
    attribute_names -= options[:except]
  end

  method_names = options[:methods].inject([]) do |methods, name|
    methods << name if respond_to?(name)
    methods
  end

  (attribute_names + method_names).inject({}) { |hash, name|
    hash[name] = send(name) if respond_to?(name)
    hash
  }
end