Class: MongoMapper::Plugins::Serialization::Serializer

Inherits:
Object
  • Object
show all
Defined in:
lib/mongo_mapper/plugins/serialization.rb

Direct Known Subclasses

Json::JsonSerializer

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(record, options = {}) ⇒ Serializer

Returns a new instance of Serializer.



13
14
15
# File 'lib/mongo_mapper/plugins/serialization.rb', line 13

def initialize(record, options={})
  @record, @options = record, options.dup
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



11
12
13
# File 'lib/mongo_mapper/plugins/serialization.rb', line 11

def options
  @options
end

Instance Method Details

#serializable_key_namesObject



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/mongo_mapper/plugins/serialization.rb', line 17

def serializable_key_names
  key_names = @record.attributes.keys

  if options[:only]
    options.delete(:except)
    key_names = key_names & Array(options[:only]).collect { |n| n.to_s }
  else
    options[:except] = Array(options[:except])
    key_names = key_names - options[:except].collect { |n| n.to_s }
  end

  key_names
end

#serializable_method_namesObject



31
32
33
34
35
36
# File 'lib/mongo_mapper/plugins/serialization.rb', line 31

def serializable_method_names
  Array(options[:methods]).inject([]) do |method_attributes, name|
    method_attributes << name if @record.respond_to?(name.to_s)
    method_attributes
  end
end

#serializable_namesObject



38
39
40
# File 'lib/mongo_mapper/plugins/serialization.rb', line 38

def serializable_names
  serializable_key_names + serializable_method_names
end

#serializable_recordObject



42
43
44
45
46
# File 'lib/mongo_mapper/plugins/serialization.rb', line 42

def serializable_record
  returning(serializable_record = {}) do
    serializable_names.each { |name| serializable_record[name] = @record.send(name) }
  end
end

#serializeObject



48
49
50
# File 'lib/mongo_mapper/plugins/serialization.rb', line 48

def serialize
  # overwrite to implement
end

#to_s(&block) ⇒ Object



52
53
54
# File 'lib/mongo_mapper/plugins/serialization.rb', line 52

def to_s(&block)
  serialize(&block)
end