Class: MongoDoc::Associations::HashProxy

Inherits:
Object
  • Object
show all
Includes:
ProxyBase
Defined in:
lib/mongodoc/associations/hash_proxy.rb

Constant Summary collapse

HASH_METHODS =
(Hash.instance_methods - Object.instance_methods).map { |n| n.to_s }
MUST_DEFINE =
%w[to_a inspect to_bson ==]
DO_NOT_DEFINE =
%w[merge! replace store update]

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from ProxyBase

#_parent=, #_path_to_root, #attach, included

Constructor Details

#initialize(options) ⇒ HashProxy

Returns a new instance of HashProxy.



31
32
33
34
# File 'lib/mongodoc/associations/hash_proxy.rb', line 31

def initialize(options)
  super
  @hash = {}
end

Instance Attribute Details

#hashObject (readonly)

Returns the value of attribute hash.



22
23
24
# File 'lib/mongodoc/associations/hash_proxy.rb', line 22

def hash
  @hash
end

Instance Method Details

#[]=(key, value) ⇒ Object Also known as: store



37
38
39
40
41
# File 'lib/mongodoc/associations/hash_proxy.rb', line 37

def []=(key, value)
  raise InvalidEmbeddedHashKey.new("Key name [#{key}] must be a valid element name, see http://www.mongodb.org/display/DOCS/BSON#BSON-noteonelementname") unless valid_key?(key)
  attach(value)
  put(key, value)
end

#_root=(root) ⇒ Object



24
25
26
27
28
29
# File 'lib/mongodoc/associations/hash_proxy.rb', line 24

def _root=(root)
  @_root = root
  hash.each do |key, value|
    value._root = root if is_document?(value)
  end
end

#build(key, attrs) ⇒ Object



44
45
46
47
# File 'lib/mongodoc/associations/hash_proxy.rb', line 44

def build(key, attrs)
  item = assoc_class.new(attrs)
  store(key, item)
end

#is_a?(klass) ⇒ Boolean Also known as: kind_of?

Lie about our class. Borrowed from Rake::FileList Note: Does not work for case equality (===)

Returns:

  • (Boolean)


51
52
53
# File 'lib/mongodoc/associations/hash_proxy.rb', line 51

def is_a?(klass)
  klass == Hash || super(klass)
end

#merge!(other) ⇒ Object Also known as: update



56
57
58
59
60
61
62
63
64
# File 'lib/mongodoc/associations/hash_proxy.rb', line 56

def merge!(other)
  other.each_pair do |key, value|
    self[key] = if block_given?
      yield key, [key], value
    else
      value
    end
  end
end

#putObject



36
# File 'lib/mongodoc/associations/hash_proxy.rb', line 36

alias put []=

#replace(other) ⇒ Object



67
68
69
70
# File 'lib/mongodoc/associations/hash_proxy.rb', line 67

def replace(other)
  clear
  merge!(other)
end

#valid?Boolean

Returns:

  • (Boolean)


72
73
74
75
76
77
78
79
80
# File 'lib/mongodoc/associations/hash_proxy.rb', line 72

def valid?
  values.all? do |child|
    if is_document?(child)
      child.valid?
    else
      true
    end
  end
end