Module: MongoLight::EmbeddedDocument::ClassMethods

Defined in:
lib/mongo_light/embedded_document.rb

Instance Method Summary collapse

Instance Method Details

#map(raw) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/mongo_light/embedded_document.rb', line 20

def map(raw)
  return {} if raw.nil? || !raw.is_a?(Hash)
  hash = {}
  raw.each do |key, value|
    sym = key.to_sym
    if value.is_a?(EmbeddedDocument)
      v = value.class.map(value.attributes)
    elsif value.is_a?(Hash)
      v = map(value)
    elsif value.is_a?(Array) && @map[sym].is_a?(Hash) && @map[sym][:array]
      v = value.map{|vv| vv.class.map(vv.attributes)}
    else
      v = value
    end
    hash[map_key(sym)] = v
  end
  return hash
end

#map_include?(key) ⇒ Boolean

Returns:

  • (Boolean)


67
68
69
# File 'lib/mongo_light/embedded_document.rb', line 67

def map_include?(key)
  @map.include?(key)
end

#map_key(key) ⇒ Object



63
64
65
66
# File 'lib/mongo_light/embedded_document.rb', line 63

def map_key(key)
  return key unless @map.include?(key)
  @map[key].is_a?(Hash) ? @map[key][:field] : @map[key]
end

#map_options(options) ⇒ Object



38
39
40
41
42
# File 'lib/mongo_light/embedded_document.rb', line 38

def map_options(options)
  options[:fields] = map(options[:fields]) if options.include?(:fields)
  options[:sort][0] = map_key(options[:sort][0]) if options.include?(:sort)
  options
end

#mongo_accessor(map) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/mongo_light/embedded_document.rb', line 7

def mongo_accessor(map)
  @map = map
  @unmap = {}
  map.each do |k,v|
    define_method(k) { @attributes[k] }
    define_method("#{k}=") {|value| @attributes[k] = value }
    if v.is_a?(Hash)
      @unmap[v[:field].to_s] = {:prop => k, :class => v[:class], :array => v[:array]}
    else
      @unmap[v.to_s] = k
    end
  end
end

#unmap(data, raw = false) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/mongo_light/embedded_document.rb', line 43

def unmap(data, raw = false)
  return {} if data.nil? || !data.is_a?(Hash)
  hash = {}
  data.each do |key, value|
    if @unmap[key].is_a?(Hash)
      real_key = @unmap[key][:prop]
      c = @unmap[key][:class]
      if @unmap[key][:array]
        v = value.map{|vv| raw ? c.unmap(vv) : c.new(c.unmap(vv))}
      else
        v = raw ? c.unmap(value) : c.new(c.unmap(value))
      end
    else
      real_key = key == '_id' ? :_id : @unmap[key]
      v = value
    end
    hash[real_key] = v
  end
  hash
end