mongoo 0.1.2

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,5 @@
1
+ lib/**/*.rb
2
+ bin/*
3
+ -
4
+ features/**/*.feature
5
+ LICENSE.txt
data/.rvmrc ADDED
@@ -0,0 +1 @@
1
+ rvm use 1.9.2@mongoo --create
data/Gemfile ADDED
@@ -0,0 +1,20 @@
1
+ source "http://rubygems.org"
2
+ # Add dependencies required to use your gem here.
3
+ # Example:
4
+
5
+ gem "i18n", ">= 0.4.1"
6
+ gem "activesupport", ">= 3.0.3"
7
+ gem "activemodel", ">= 3.0.3"
8
+ gem "bson_ext", ">= 1.2.4"
9
+ gem "mongo", ">= 1.2.4"
10
+
11
+ gem "em-synchrony", ">= 0.2.0"
12
+
13
+ # Add dependencies to develop your gem here.
14
+ # Include everything needed to run rake, tests, features, etc.
15
+ group :development do
16
+ gem "shoulda", ">= 0"
17
+ gem "bundler", "~> 1.0.0"
18
+ gem "jeweler", "~> 1.5.1"
19
+ gem "rcov", ">= 0"
20
+ end
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2010 Ben Myles
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,19 @@
1
+ = mongoo
2
+
3
+ Description goes here.
4
+
5
+ == Contributing to mongoo
6
+
7
+ * Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
8
+ * Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it
9
+ * Fork the project
10
+ * Start a feature/bugfix branch
11
+ * Commit and push until you are happy with your contribution
12
+ * Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
13
+ * Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
14
+
15
+ == Copyright
16
+
17
+ Copyright (c) 2010 Ben Myles. See LICENSE.txt for
18
+ further details.
19
+
@@ -0,0 +1,53 @@
1
+ require 'rubygems'
2
+ require 'bundler'
3
+ begin
4
+ Bundler.setup(:default, :development)
5
+ rescue Bundler::BundlerError => e
6
+ $stderr.puts e.message
7
+ $stderr.puts "Run `bundle install` to install missing gems"
8
+ exit e.status_code
9
+ end
10
+ require 'rake'
11
+
12
+ require 'jeweler'
13
+ Jeweler::Tasks.new do |gem|
14
+ # gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options
15
+ gem.name = "mongoo"
16
+ gem.homepage = "http://github.com/benmyles/mongoo"
17
+ gem.license = "MIT"
18
+ gem.summary = %Q{Object mapper for MongoDB}
19
+ gem.description = %Q{Simple object mapper for MongoDB}
20
+ gem.email = "ben.myles@gmail.com"
21
+ gem.authors = ["Ben Myles"]
22
+ # Include your dependencies below. Runtime dependencies are required when using your gem,
23
+ # and development dependencies are only needed for development (ie running rake tasks, tests, etc)
24
+ # gem.add_runtime_dependency 'jabber4r', '> 0.1'
25
+ # gem.add_development_dependency 'rspec', '> 1.2.3'
26
+ end
27
+ Jeweler::RubygemsDotOrgTasks.new
28
+
29
+ require 'rake/testtask'
30
+ Rake::TestTask.new(:test) do |test|
31
+ test.libs << 'lib' << 'test'
32
+ test.pattern = 'test/**/test_*.rb'
33
+ test.verbose = true
34
+ end
35
+
36
+ require 'rcov/rcovtask'
37
+ Rcov::RcovTask.new do |test|
38
+ test.libs << 'test'
39
+ test.pattern = 'test/**/test_*.rb'
40
+ test.verbose = true
41
+ end
42
+
43
+ task :default => :test
44
+
45
+ require 'rake/rdoctask'
46
+ Rake::RDocTask.new do |rdoc|
47
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
48
+
49
+ rdoc.rdoc_dir = 'rdoc'
50
+ rdoc.title = "mongoo #{version}"
51
+ rdoc.rdoc_files.include('README*')
52
+ rdoc.rdoc_files.include('lib/**/*.rb')
53
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.1.2
@@ -0,0 +1,49 @@
1
+ module Mongoo
2
+ INDEX_META = {}
3
+ ATTRIBUTE_META = {}
4
+
5
+ def self.config
6
+ { host: "127.0.0.1",
7
+ port: 27017,
8
+ db: "test",
9
+ opts: {}}.merge(@config || {})
10
+ end
11
+
12
+ def self.config=(cfg)
13
+ @config = cfg
14
+ end
15
+
16
+ def self.conn
17
+ @conn ||= Mongo::Connection.new(config[:host], config[:port], config[:opts])
18
+ end
19
+
20
+ def self.db
21
+ @db ||= conn.db(config[:db])
22
+ end
23
+
24
+ def self.verbose_debug
25
+ @verbose_debug
26
+ end
27
+
28
+ def self.verbose_debug=(val)
29
+ @verbose_debug = val
30
+ end
31
+ end
32
+
33
+ require "forwardable"
34
+ require "mongo"
35
+
36
+ require "mongoo/async"
37
+
38
+ require "active_support/core_ext"
39
+ require "active_model"
40
+
41
+ require "mongoo/hash_ext"
42
+ require "mongoo/cursor"
43
+ require "mongoo/attribute_sanitizer"
44
+ require "mongoo/attribute_proxy"
45
+ require "mongoo/changelog"
46
+ require "mongoo/persistence"
47
+ require "mongoo/modifiers"
48
+ require "mongoo/base"
49
+ require "mongoo/mongohash"
@@ -0,0 +1,41 @@
1
+ if ENV["MONGOO_ASYNC"] == "1" || (ENV["MONGOO_SYNC"] != "1" && (defined?(EM) && EM.reactor_running?))
2
+ require "em-synchrony"
3
+ require "em-synchrony/tcpsocket"
4
+ module Mongo
5
+ class Connection
6
+ EMTCPSocket = ::EventMachine::Synchrony::TCPSocket
7
+
8
+ def check_is_master(node)
9
+ begin
10
+ host, port = *node
11
+ socket = EMTCPSocket.new(host, port)
12
+ socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
13
+
14
+ config = self['admin'].command({:ismaster => 1}, :socket => socket)
15
+ rescue OperationFailure, SocketError, SystemCallError, IOError => ex
16
+ close
17
+ ensure
18
+ socket.close if socket
19
+ end
20
+
21
+ config
22
+ end
23
+ end
24
+ end
25
+
26
+ module Mongoo
27
+ def self.mode
28
+ :async
29
+ end
30
+ end
31
+
32
+ puts "* Mongoo Running in Asynchronous Mode" if ENV["MONGOO_DEBUG"] == "1"
33
+ else
34
+ module Mongoo
35
+ def self.mode
36
+ :sync
37
+ end
38
+ end
39
+
40
+ puts "* Mongoo Running in Synchronous Mode" if ENV["MONGOO_DEBUG"] == "1"
41
+ end
@@ -0,0 +1,47 @@
1
+ module Mongoo
2
+ class AttributeProxy
3
+
4
+ def initialize(curr_hash, path, doc)
5
+ @curr_hash = curr_hash
6
+ @path = path
7
+ @doc = doc
8
+ end
9
+
10
+ def unset
11
+ @doc.unset @path.join(".")
12
+ end
13
+
14
+ def mod(opts={}, &block)
15
+ builder = ModifierBuilder.new(opts.merge(:key_prefix => "#{@path.join(".")}."), @doc)
16
+ block.call(builder)
17
+ builder.run!
18
+ end
19
+
20
+ def mod!(opts={}, &block)
21
+ mod(opts.merge(:safe => true), &block)
22
+ end
23
+
24
+ def method_missing(name, *args)
25
+ name_s = name.to_s
26
+ setter = false
27
+ setter = true if name_s =~ /\=$/
28
+ name_s.gsub!(/\=$/, '')
29
+
30
+ if val = @curr_hash[name_s]
31
+ key = (@path + [name_s]).join(".")
32
+ if val.is_a?(Hash) && !@doc.known_attribute?(key)
33
+ if setter
34
+ super
35
+ else
36
+ AttributeProxy.new(val, (@path + [name_s]), @doc)
37
+ end
38
+ else
39
+ setter ? @doc.set(key, args[0]) : @doc.get(key)
40
+ end
41
+ else
42
+ super
43
+ end
44
+ end
45
+
46
+ end
47
+ end
@@ -0,0 +1,41 @@
1
+ module Mongoo
2
+ class InvalidAttributeValue < Exception; end
3
+
4
+ class AttributeSanitizer
5
+ class << self
6
+ def sanitize(field_type, val)
7
+ return val if val.nil? || field_type.nil?
8
+
9
+ case field_type.to_sym
10
+ when :string then
11
+ val.is_a?(String) ? val : val.to_s
12
+ when :symbol then
13
+ val.is_a?(Symbol) ? val : val.to_sym
14
+ when :integer then
15
+ val.is_a?(Fixnum) ? val : val.to_i
16
+ when :float then
17
+ val.is_a?(Float) ? val : val.to_f
18
+ when :array then
19
+ val.is_a?(Array) ? val : [val]
20
+ when :bson_object_id then
21
+ val.is_a?(BSON::ObjectId) ? val : BSON::ObjectId(val)
22
+ when :hash then
23
+ val.is_a?(Hash) ? val : raise(InvalidAttributeValue, val.inspect)
24
+ when :time then
25
+ Time.parse(val.to_s)
26
+ # val.is_a?(Time) ? val : Time.parse(val)
27
+ when :bool then
28
+ if [true,false].include?(val)
29
+ val
30
+ elsif ["t","1","true","y","yes"].include?(val.to_s.downcase)
31
+ true
32
+ elsif ["f","0","false","n","no"].include?(val.to_s.downcase)
33
+ false
34
+ end
35
+ when :html_escaped_string then
36
+ ERB::Util.html_escape(val.to_s)
37
+ end # case
38
+ end # sanitize
39
+ end # << self
40
+ end # AttributeSanitizer
41
+ end # Mongoo
@@ -0,0 +1,209 @@
1
+ module Mongoo
2
+ class UnknownAttributeError < Exception; end
3
+
4
+ class Base
5
+
6
+ include Mongoo::Changelog
7
+ include Mongoo::Persistence
8
+ include Mongoo::Modifiers
9
+
10
+ include ActiveModel::Validations
11
+
12
+ extend ActiveModel::Callbacks
13
+ extend ActiveModel::Naming
14
+
15
+ define_model_callbacks :insert, :update, :remove
16
+
17
+ def self.attribute(name, opts={})
18
+ raise ArgumentError.new("missing :type") unless opts[:type]
19
+ self.attributes[name.to_s] = opts
20
+ define_attribute_methods
21
+ true
22
+ end
23
+
24
+ def self.attributes
25
+ Mongoo::ATTRIBUTE_META[self.to_s] ||= {}
26
+ end
27
+
28
+ def self.attributes_tree
29
+ tree = {}
30
+ self.attributes.each do |name, opts|
31
+ parts = name.split(".")
32
+ curr_branch = tree
33
+ while part = parts.shift
34
+ if !parts.empty?
35
+ curr_branch[part.to_s] ||= {}
36
+ curr_branch = curr_branch[part.to_s]
37
+ else
38
+ curr_branch[part.to_s] = opts[:type]
39
+ end
40
+ end
41
+ end
42
+ tree
43
+ end
44
+
45
+ def self.define_attribute_methods
46
+ define_method("id") do
47
+ get("_id")
48
+ end
49
+ define_method("id=") do |val|
50
+ set("_id", val)
51
+ end
52
+
53
+ self.attributes_tree.each do |name, val|
54
+ if val.is_a?(Hash)
55
+ define_method(name) do
56
+ AttributeProxy.new(val, [name], self)
57
+ end
58
+ else
59
+ define_method(name) do
60
+ get(name)
61
+ end
62
+ define_method("#{name}=") do |val|
63
+ set(name, val)
64
+ end
65
+ end
66
+ end
67
+ end
68
+
69
+ def self.known_attribute?(k)
70
+ k == "_id" || self.attributes[k.to_s]
71
+ end
72
+
73
+ def initialize(hash={}, persisted=false)
74
+ @persisted = persisted
75
+ init_from_hash(hash)
76
+ set_persisted_mongohash((persisted? ? mongohash.deep_clone : nil))
77
+ end
78
+
79
+ def ==(val)
80
+ if val.class.to_s == self.class.to_s
81
+ if val.persisted?
82
+ val.id == self.id
83
+ else
84
+ self.mongohash.raw_hash == val.mongohash.raw_hash
85
+ end
86
+ end
87
+ end
88
+
89
+ def known_attribute?(k)
90
+ self.class.known_attribute?(k)
91
+ end
92
+
93
+ def read_attribute_for_validation(key)
94
+ get_attribute(key)
95
+ end
96
+
97
+ def get_attribute(k)
98
+ unless known_attribute?(k)
99
+ raise UnknownAttributeError, k
100
+ end
101
+ mongohash.dot_get(k.to_s)
102
+ end
103
+ alias :get :get_attribute
104
+ alias :g :get_attribute
105
+
106
+ def set_attribute(k,v)
107
+ unless known_attribute?(k)
108
+ if self.respond_to?("#{k}=")
109
+ return self.send("#{k}=", v)
110
+ else
111
+ raise UnknownAttributeError, k
112
+ end
113
+ end
114
+ unless k.to_s == "_id" || v.nil?
115
+ field_type = self.class.attributes[k.to_s][:type]
116
+ v = Mongoo::AttributeSanitizer.sanitize(field_type, v)
117
+ end
118
+ mongohash.dot_set(k.to_s,v)
119
+ end
120
+ alias :set :set_attribute
121
+ alias :s :set_attribute
122
+
123
+ def unset_attribute(k)
124
+ mongohash.dot_delete(k); true
125
+ end
126
+ alias :unset :unset_attribute
127
+ alias :u :unset_attribute
128
+
129
+ def set_attributes(k_v_pairs)
130
+ k_v_pairs.each do |k,v|
131
+ set_attribute(k,v)
132
+ end
133
+ end
134
+ alias :sets :set_attributes
135
+
136
+ def get_attributes(keys)
137
+ found = {}
138
+ keys.each { |k| found[k.to_s] = get_attribute(k) }
139
+ found
140
+ end
141
+ alias :gets :get_attributes
142
+
143
+ def unset_attributes(keys)
144
+ keys.each { |k| unset_attribute(k) }; true
145
+ end
146
+ alias :unsets :unset_attributes
147
+
148
+ def attributes
149
+ mongohash.to_key_value
150
+ end
151
+
152
+ def merge!(hash)
153
+ if hash.is_a?(Mongoo::Mongohash)
154
+ hash = hash.raw_hash
155
+ end
156
+ hash.deep_stringify_keys!
157
+ hash = mongohash.raw_hash.deep_merge(hash)
158
+ set_mongohash( Mongoo::Mongohash.new(hash) )
159
+ mongohash
160
+ end
161
+
162
+ def init_from_hash(hash)
163
+ unless hash.is_a?(Mongoo::Mongohash)
164
+ hash = Mongoo::Mongohash.new(hash)
165
+ end
166
+ verify_attributes_in_mongohash(hash)
167
+ set_mongohash hash
168
+ end
169
+ protected :init_from_hash
170
+
171
+ def set_mongohash(mongohash)
172
+ @mongohash = mongohash
173
+ end
174
+ protected :set_mongohash
175
+
176
+ def mongohash
177
+ @mongohash
178
+ end
179
+
180
+ def set_persisted_mongohash(hash)
181
+ @persisted_mongohash = hash
182
+ end
183
+ protected :set_persisted_mongohash
184
+
185
+ def persisted_mongohash
186
+ @persisted_mongohash
187
+ end
188
+
189
+ def verify_attributes_in_mongohash(hash)
190
+ known_keys = self.class.attributes.keys
191
+ known_keys << "_id"
192
+ hash.dot_list.each do |k|
193
+ unless known_keys.include?(k)
194
+ k.split(".").each do |part|
195
+ if opts = self.class.attributes[part]
196
+ if opts[:type] == :hash
197
+ known_keys << k
198
+ end
199
+ end
200
+ end
201
+ unless known_keys.include?(k)
202
+ # this is just annoying.
203
+ #raise Mongoo::UnknownAttributeError, k.to_s
204
+ end
205
+ end
206
+ end
207
+ end # verify_attributes_in_mongohash
208
+ end
209
+ end