Module: MongoMapper::Plugins::Serialization::InstanceMethods

Defined in:
lib/mongo_mapper/plugins/serialization.rb

Instance Method Summary collapse

Instance Method Details

#as_json(options = {}) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/mongo_mapper/plugins/serialization.rb', line 11

def as_json options={}
  options ||= {}
  unless options[:only]
    methods = [options.delete(:methods)].flatten.compact
    methods << :id
    options[:methods] = methods.uniq
  end

  except = [options.delete(:except)].flatten.compact
  except << :_id
  options[:except] = except

  # Direct rip from Rails 3 ActiveModel Serialization (#serializable_hash)
  hash = begin
    options[:only]   = Array.wrap(options[:only]).map { |n| n.to_s }
    options[:except] = Array.wrap(options[:except]).map { |n| n.to_s }

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

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

    (attribute_names + method_names).inject({}) { |hash, name|
      hash[name] = send(name)
      hash
    }
  end
  # End rip
  
  options.delete(:only) if options[:only].nil? or options[:only].empty?

  hash.each do |key, value|
    if value.is_a?(Array)
      hash[key] = value.map do |item|
        item.respond_to?(:as_json) ? item.as_json(options) : item
      end
    elsif value.is_a? Mongo::ObjectID
      hash[key] = value.to_s
    elsif value.respond_to?(:as_json)
      hash[key] = value.as_json(options)
    end
  end
  
  # Replicate Rails 3 naming - and also bin anytihng after : for use in our dynamic classes from unit tests
  hash = { ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(self)).gsub(/:.*/,'') => hash } if include_root_in_json
  hash
end