nobrainer 0.11.0 → 0.12.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (39) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +169 -0
  3. data/lib/no_brainer/criteria.rb +4 -16
  4. data/lib/no_brainer/criteria/after_find.rb +24 -0
  5. data/lib/no_brainer/criteria/{termination/cache.rb → cache.rb} +1 -1
  6. data/lib/no_brainer/criteria/{chainable/core.rb → core.rb} +1 -1
  7. data/lib/no_brainer/criteria/{termination/count.rb → count.rb} +1 -1
  8. data/lib/no_brainer/criteria/{termination/delete.rb → delete.rb} +1 -1
  9. data/lib/no_brainer/criteria/{termination/enumerable.rb → enumerable.rb} +1 -1
  10. data/lib/no_brainer/criteria/{termination/first.rb → first.rb} +1 -1
  11. data/lib/no_brainer/criteria/{termination/inc.rb → inc.rb} +1 -1
  12. data/lib/no_brainer/criteria/{chainable/limit.rb → limit.rb} +1 -1
  13. data/lib/no_brainer/criteria/{chainable/order_by.rb → order_by.rb} +1 -1
  14. data/lib/no_brainer/criteria/{termination/preload.rb → preload.rb} +3 -3
  15. data/lib/no_brainer/criteria/raw.rb +25 -0
  16. data/lib/no_brainer/criteria/{chainable/scope.rb → scope.rb} +1 -1
  17. data/lib/no_brainer/criteria/{termination/update.rb → update.rb} +1 -1
  18. data/lib/no_brainer/criteria/{chainable/where.rb → where.rb} +22 -13
  19. data/lib/no_brainer/document.rb +2 -2
  20. data/lib/no_brainer/document/association/belongs_to.rb +5 -0
  21. data/lib/no_brainer/document/association/core.rb +2 -2
  22. data/lib/no_brainer/document/association/has_many.rb +1 -1
  23. data/lib/no_brainer/document/attributes.rb +2 -15
  24. data/lib/no_brainer/document/callbacks.rb +5 -0
  25. data/lib/no_brainer/document/dirty.rb +0 -18
  26. data/lib/no_brainer/document/id.rb +1 -1
  27. data/lib/no_brainer/document/index.rb +0 -5
  28. data/lib/no_brainer/document/persistance.rb +32 -19
  29. data/lib/no_brainer/document/serialization.rb +0 -1
  30. data/lib/no_brainer/document/timestamps.rb +10 -12
  31. data/lib/no_brainer/document/types.rb +23 -28
  32. data/lib/no_brainer/document_with_timestamps.rb +6 -0
  33. data/lib/no_brainer/error.rb +26 -9
  34. data/lib/no_brainer/query_runner/missing_index.rb +1 -1
  35. data/lib/no_brainer/railtie.rb +10 -0
  36. data/lib/nobrainer.rb +3 -3
  37. metadata +37 -35
  38. data/LICENSE.md +0 -7
  39. data/lib/no_brainer/criteria/chainable/raw.rb +0 -33
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: 56f5bfdef46fb94e140efe80af84031e02238d07
4
- data.tar.gz: aa5965b806a43a8727be98ef2a7a9c370fe94cfc
3
+ metadata.gz: f9f0fb2d3cb21fba6fad94403706e6f5274f72f4
4
+ data.tar.gz: 74bfea6252ccc4eee6e67c003ed3facc7bbffe69
5
5
  SHA512:
6
- metadata.gz: 0285cc6834d21a4e973fe293adf54ada0bcce15424a605719a32db2445a909793ebab766549a9d8b31b42ced44e6d3ef5f1cfecd980b33b4c4c1792af94a74c4
7
- data.tar.gz: 3ed81e4508bc4528142b7049db0e1464927f7dfcad9c459853593c70a9ebbed95c47b3bd634d03f0bc2e9ebcc358a2d72cbcd7b7c73b4c46ca37a518a23c7c56
6
+ metadata.gz: 8da93f62774128bc6bfc485c356fd1e27b68ae0f3c5ccd0e9e81545210856a9282dccf0936369d3b92da90904e598d1c16d264a36b82e050e328ad02bda2758c
7
+ data.tar.gz: c8f6e9c112d89df7062d2ffde33952e688d6c7c47becde0d3391949abac41851149a3d3625025908f00429565152157366bf90d1147bf4d0e705e68e57b1c31a
data/LICENSE ADDED
@@ -0,0 +1,169 @@
1
+ Copyright (c) Nicolas Viennot
2
+
3
+ NoBrainer is licensed under the terms of the LGPLv3 license.
4
+
5
+ GNU LESSER GENERAL PUBLIC LICENSE
6
+ Version 3, 29 June 2007
7
+
8
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
9
+ Everyone is permitted to copy and distribute verbatim copies
10
+ of this license document, but changing it is not allowed.
11
+
12
+
13
+ This version of the GNU Lesser General Public License incorporates
14
+ the terms and conditions of version 3 of the GNU General Public
15
+ License, supplemented by the additional permissions listed below.
16
+
17
+ 0. Additional Definitions.
18
+
19
+ As used herein, "this License" refers to version 3 of the GNU Lesser
20
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
21
+ General Public License.
22
+
23
+ "The Library" refers to a covered work governed by this License,
24
+ other than an Application or a Combined Work as defined below.
25
+
26
+ An "Application" is any work that makes use of an interface provided
27
+ by the Library, but which is not otherwise based on the Library.
28
+ Defining a subclass of a class defined by the Library is deemed a mode
29
+ of using an interface provided by the Library.
30
+
31
+ A "Combined Work" is a work produced by combining or linking an
32
+ Application with the Library. The particular version of the Library
33
+ with which the Combined Work was made is also called the "Linked
34
+ Version".
35
+
36
+ The "Minimal Corresponding Source" for a Combined Work means the
37
+ Corresponding Source for the Combined Work, excluding any source code
38
+ for portions of the Combined Work that, considered in isolation, are
39
+ based on the Application, and not on the Linked Version.
40
+
41
+ The "Corresponding Application Code" for a Combined Work means the
42
+ object code and/or source code for the Application, including any data
43
+ and utility programs needed for reproducing the Combined Work from the
44
+ Application, but excluding the System Libraries of the Combined Work.
45
+
46
+ 1. Exception to Section 3 of the GNU GPL.
47
+
48
+ You may convey a covered work under sections 3 and 4 of this License
49
+ without being bound by section 3 of the GNU GPL.
50
+
51
+ 2. Conveying Modified Versions.
52
+
53
+ If you modify a copy of the Library, and, in your modifications, a
54
+ facility refers to a function or data to be supplied by an Application
55
+ that uses the facility (other than as an argument passed when the
56
+ facility is invoked), then you may convey a copy of the modified
57
+ version:
58
+
59
+ a) under this License, provided that you make a good faith effort to
60
+ ensure that, in the event an Application does not supply the
61
+ function or data, the facility still operates, and performs
62
+ whatever part of its purpose remains meaningful, or
63
+
64
+ b) under the GNU GPL, with none of the additional permissions of
65
+ this License applicable to that copy.
66
+
67
+ 3. Object Code Incorporating Material from Library Header Files.
68
+
69
+ The object code form of an Application may incorporate material from
70
+ a header file that is part of the Library. You may convey such object
71
+ code under terms of your choice, provided that, if the incorporated
72
+ material is not limited to numerical parameters, data structure
73
+ layouts and accessors, or small macros, inline functions and templates
74
+ (ten or fewer lines in length), you do both of the following:
75
+
76
+ a) Give prominent notice with each copy of the object code that the
77
+ Library is used in it and that the Library and its use are
78
+ covered by this License.
79
+
80
+ b) Accompany the object code with a copy of the GNU GPL and this license
81
+ document.
82
+
83
+ 4. Combined Works.
84
+
85
+ You may convey a Combined Work under terms of your choice that,
86
+ taken together, effectively do not restrict modification of the
87
+ portions of the Library contained in the Combined Work and reverse
88
+ engineering for debugging such modifications, if you also do each of
89
+ the following:
90
+
91
+ a) Give prominent notice with each copy of the Combined Work that
92
+ the Library is used in it and that the Library and its use are
93
+ covered by this License.
94
+
95
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
96
+ document.
97
+
98
+ c) For a Combined Work that displays copyright notices during
99
+ execution, include the copyright notice for the Library among
100
+ these notices, as well as a reference directing the user to the
101
+ copies of the GNU GPL and this license document.
102
+
103
+ d) Do one of the following:
104
+
105
+ 0) Convey the Minimal Corresponding Source under the terms of this
106
+ License, and the Corresponding Application Code in a form
107
+ suitable for, and under terms that permit, the user to
108
+ recombine or relink the Application with a modified version of
109
+ the Linked Version to produce a modified Combined Work, in the
110
+ manner specified by section 6 of the GNU GPL for conveying
111
+ Corresponding Source.
112
+
113
+ 1) Use a suitable shared library mechanism for linking with the
114
+ Library. A suitable mechanism is one that (a) uses at run time
115
+ a copy of the Library already present on the user's computer
116
+ system, and (b) will operate properly with a modified version
117
+ of the Library that is interface-compatible with the Linked
118
+ Version.
119
+
120
+ e) Provide Installation Information, but only if you would otherwise
121
+ be required to provide such information under section 6 of the
122
+ GNU GPL, and only to the extent that such information is
123
+ necessary to install and execute a modified version of the
124
+ Combined Work produced by recombining or relinking the
125
+ Application with a modified version of the Linked Version. (If
126
+ you use option 4d0, the Installation Information must accompany
127
+ the Minimal Corresponding Source and Corresponding Application
128
+ Code. If you use option 4d1, you must provide the Installation
129
+ Information in the manner specified by section 6 of the GNU GPL
130
+ for conveying Corresponding Source.)
131
+
132
+ 5. Combined Libraries.
133
+
134
+ You may place library facilities that are a work based on the
135
+ Library side by side in a single library together with other library
136
+ facilities that are not Applications and are not covered by this
137
+ License, and convey such a combined library under terms of your
138
+ choice, if you do both of the following:
139
+
140
+ a) Accompany the combined library with a copy of the same work based
141
+ on the Library, uncombined with any other library facilities,
142
+ conveyed under the terms of this License.
143
+
144
+ b) Give prominent notice with the combined library that part of it
145
+ is a work based on the Library, and explaining where to find the
146
+ accompanying uncombined form of the same work.
147
+
148
+ 6. Revised Versions of the GNU Lesser General Public License.
149
+
150
+ The Free Software Foundation may publish revised and/or new versions
151
+ of the GNU Lesser General Public License from time to time. Such new
152
+ versions will be similar in spirit to the present version, but may
153
+ differ in detail to address new problems or concerns.
154
+
155
+ Each version is given a distinguishing version number. If the
156
+ Library as you received it specifies that a certain numbered version
157
+ of the GNU Lesser General Public License "or any later version"
158
+ applies to it, you have the option of following the terms and
159
+ conditions either of that published version or of any later version
160
+ published by the Free Software Foundation. If the Library as you
161
+ received it does not specify a version number of the GNU Lesser
162
+ General Public License, you may choose any version of the GNU Lesser
163
+ General Public License ever published by the Free Software Foundation.
164
+
165
+ If the Library as you received it specifies that a proxy can decide
166
+ whether future versions of the GNU Lesser General Public License shall
167
+ apply, that proxy's public statement of acceptance of any version is
168
+ permanent authorization for you to choose that version for the
169
+ Library.
@@ -1,20 +1,8 @@
1
1
  require 'rethinkdb'
2
2
 
3
3
  class NoBrainer::Criteria
4
- # The disctinction between Chainable and Termination is purely cosmetic.
5
- module Chainable
6
- extend NoBrainer::Autoload
7
- extend ActiveSupport::Concern
8
- autoload_and_include :Core, :Scope, :Raw, :Where, :OrderBy, :Limit
9
- end
10
-
11
- module Termination
12
- extend NoBrainer::Autoload
13
- extend ActiveSupport::Concern
14
- autoload_and_include :Count, :Delete, :Enumerable, :First, :Preload,
15
- :Inc, :Update, :Cache
16
- end
17
-
18
- include Chainable
19
- include Termination
4
+ extend NoBrainer::Autoload
5
+ autoload_and_include :Core, :Scope, :Raw, :AfterFind, :Where, :OrderBy, :Limit,
6
+ :Count, :Delete, :Enumerable, :First, :Preload, :Inc,
7
+ :Update, :Cache
20
8
  end
@@ -0,0 +1,24 @@
1
+ module NoBrainer::Criteria::AfterFind
2
+ extend ActiveSupport::Concern
3
+
4
+ included { attr_accessor :_after_find }
5
+
6
+ def after_find(b=nil, &block)
7
+ chain { |criteria| criteria._after_find = [b || block] }
8
+ end
9
+
10
+ def merge!(criteria, options={})
11
+ super
12
+ if criteria._after_find.present?
13
+ self._after_find = (self._after_find || []) + criteria._after_find
14
+ end
15
+ self
16
+ end
17
+
18
+ def instantiate_doc(attrs)
19
+ super.tap do |doc|
20
+ self._after_find.to_a.each { |block| block.call(doc) }
21
+ doc.run_callbacks(:find) if doc.is_a?(NoBrainer::Document)
22
+ end
23
+ end
24
+ end
@@ -1,4 +1,4 @@
1
- module NoBrainer::Criteria::Termination::Cache
1
+ module NoBrainer::Criteria::Cache
2
2
  extend ActiveSupport::Concern
3
3
 
4
4
  included { attr_accessor :_with_cache }
@@ -1,4 +1,4 @@
1
- module NoBrainer::Criteria::Chainable::Core
1
+ module NoBrainer::Criteria::Core
2
2
  extend ActiveSupport::Concern
3
3
 
4
4
  included { attr_accessor :init_options }
@@ -1,4 +1,4 @@
1
- module NoBrainer::Criteria::Termination::Count
1
+ module NoBrainer::Criteria::Count
2
2
  extend ActiveSupport::Concern
3
3
 
4
4
  def count
@@ -1,4 +1,4 @@
1
- module NoBrainer::Criteria::Termination::Delete
1
+ module NoBrainer::Criteria::Delete
2
2
  extend ActiveSupport::Concern
3
3
 
4
4
  def delete_all
@@ -1,4 +1,4 @@
1
- module NoBrainer::Criteria::Termination::Enumerable
1
+ module NoBrainer::Criteria::Enumerable
2
2
  extend ActiveSupport::Concern
3
3
 
4
4
  def each(options={}, &block)
@@ -1,4 +1,4 @@
1
- module NoBrainer::Criteria::Termination::First
1
+ module NoBrainer::Criteria::First
2
2
  extend ActiveSupport::Concern
3
3
 
4
4
  def first
@@ -1,4 +1,4 @@
1
- module NoBrainer::Criteria::Termination::Inc
1
+ module NoBrainer::Criteria::Inc
2
2
  extend ActiveSupport::Concern
3
3
 
4
4
  def inc_all(field, value=1)
@@ -1,4 +1,4 @@
1
- module NoBrainer::Criteria::Chainable::Limit
1
+ module NoBrainer::Criteria::Limit
2
2
  # TODO Test these guys
3
3
  extend ActiveSupport::Concern
4
4
 
@@ -1,4 +1,4 @@
1
- module NoBrainer::Criteria::Chainable::OrderBy
1
+ module NoBrainer::Criteria::OrderBy
2
2
  extend ActiveSupport::Concern
3
3
 
4
4
  included { attr_accessor :order, :_reverse_order }
@@ -1,4 +1,4 @@
1
- module NoBrainer::Criteria::Termination::Preload
1
+ module NoBrainer::Criteria::Preload
2
2
  extend ActiveSupport::Concern
3
3
 
4
4
  included { attr_accessor :_preloads }
@@ -28,10 +28,10 @@ module NoBrainer::Criteria::Termination::Preload
28
28
  end
29
29
 
30
30
  def each(options={}, &block)
31
- return super unless should_preloads? && !options[:no_preloadsing] && block
31
+ return super unless should_preloads? && !options[:no_preloading] && block
32
32
 
33
33
  docs = []
34
- super(options.merge(:no_preloadsing => true)) { |doc| docs << doc }
34
+ super(options.merge(:no_preloading => true)) { |doc| docs << doc }
35
35
  perform_preloads(docs)
36
36
  docs.each(&block)
37
37
  self
@@ -0,0 +1,25 @@
1
+ module NoBrainer::Criteria::Raw
2
+ extend ActiveSupport::Concern
3
+
4
+ included { attr_accessor :_raw }
5
+
6
+ def raw
7
+ chain { |criteria| criteria._raw = true }
8
+ end
9
+
10
+ def merge!(criteria, options={})
11
+ super
12
+ self._raw = criteria._raw unless criteria._raw.nil?
13
+ self
14
+ end
15
+
16
+ private
17
+
18
+ def raw?
19
+ !!_raw
20
+ end
21
+
22
+ def instantiate_doc(attrs)
23
+ raw? ? attrs : klass.new_from_db(attrs)
24
+ end
25
+ end
@@ -1,4 +1,4 @@
1
- module NoBrainer::Criteria::Chainable::Scope
1
+ module NoBrainer::Criteria::Scope
2
2
  extend ActiveSupport::Concern
3
3
 
4
4
  included { attr_accessor :use_default_scope }
@@ -1,4 +1,4 @@
1
- module NoBrainer::Criteria::Termination::Update
1
+ module NoBrainer::Criteria::Update
2
2
  extend ActiveSupport::Concern
3
3
 
4
4
  def update_all(attrs={}, &block)
@@ -1,4 +1,4 @@
1
- module NoBrainer::Criteria::Chainable::Where
1
+ module NoBrainer::Criteria::Where
2
2
  extend ActiveSupport::Concern
3
3
 
4
4
  included { attr_accessor :where_ast, :with_index_name }
@@ -54,16 +54,16 @@ module NoBrainer::Criteria::Chainable::Where
54
54
  end
55
55
  end
56
56
 
57
- class BinaryOperator < Struct.new(:key, :op, :value)
57
+ class BinaryOperator < Struct.new(:key, :op, :value, :criteria)
58
58
  def simplify
59
59
  case op
60
60
  when :in then
61
61
  case value
62
- when Range then BinaryOperator.new(key, :between, value)
63
- when Array then BinaryOperator.new(key, :in, value.uniq)
62
+ when Range then BinaryOperator.new(key, :between, (cast(value.min)..cast(value.max)), criteria)
63
+ when Array then BinaryOperator.new(key, :in, value.map(&method(:cast)).uniq, criteria)
64
64
  else raise ArgumentError.new ":in takes an array/range, not #{value}"
65
65
  end
66
- else self
66
+ else BinaryOperator.new(key, op, cast(value), criteria)
67
67
  end
68
68
  end
69
69
 
@@ -74,6 +74,12 @@ module NoBrainer::Criteria::Chainable::Where
74
74
  else doc[key].__send__(op, value)
75
75
  end
76
76
  end
77
+
78
+ private
79
+
80
+ def cast(value)
81
+ criteria.klass.cast_value_for(key, value)
82
+ end
77
83
  end
78
84
 
79
85
  class UnaryOperator < Struct.new(:op, :value)
@@ -117,22 +123,25 @@ module NoBrainer::Criteria::Chainable::Where
117
123
  when :and then MultiOperator.new(:and, value.map { |v| parse_clause(v) })
118
124
  when :or then MultiOperator.new(:or, value.map { |v| parse_clause(v) })
119
125
  when :not then UnaryOperator.new(:not, parse_clause(value))
120
- when String, Symbol then parse_clause_stub(key.to_sym.eq, value)
126
+ when String, Symbol then parse_clause_stub_eq(key, value)
121
127
  when NoBrainer::DecoratedSymbol then
122
128
  case key.modifier
123
129
  when :ne then parse_clause(:not => { key.symbol => value })
124
- when :eq then
125
- case value
126
- when Range then BinaryOperator.new(key.symbol, :between, value)
127
- when Regexp then BinaryOperator.new(key.symbol, :match, value.inspect[1..-2])
128
- else BinaryOperator.new(key.symbol, key.modifier, value)
129
- end
130
- else BinaryOperator.new(key.symbol, key.modifier, value)
130
+ when :eq then parse_clause_stub_eq(key.symbol, value)
131
+ else BinaryOperator.new(key.symbol, key.modifier, value, self)
131
132
  end
132
133
  else raise "Invalid key: #{key}"
133
134
  end
134
135
  end
135
136
 
137
+ def parse_clause_stub_eq(key, value)
138
+ case value
139
+ when Range then BinaryOperator.new(key, :between, value, self)
140
+ when Regexp then BinaryOperator.new(key, :match, value.inspect[1..-2], self)
141
+ else BinaryOperator.new(key, :eq, value, self)
142
+ end
143
+ end
144
+
136
145
  def without_index?
137
146
  self.with_index_name == false
138
147
  end
@@ -6,9 +6,9 @@ module NoBrainer::Document
6
6
 
7
7
  autoload_and_include :Core, :StoreIn, :InjectionLayer, :Attributes, :Validation, :Types,
8
8
  :Persistance, :Callbacks, :Dirty, :Id, :Association, :Serialization,
9
- :Criteria, :Polymorphic, :Index, :Timestamps
9
+ :Criteria, :Polymorphic, :Index
10
10
 
11
- autoload :DynamicAttributes
11
+ autoload :DynamicAttributes, :Timestamps
12
12
 
13
13
  singleton_class.delegate :all, :to => Core
14
14
  end
@@ -19,6 +19,11 @@ class NoBrainer::Document::Association::BelongsTo
19
19
  def hook
20
20
  super
21
21
 
22
+ # TODO It would be good to set the type we want to work with, but because
23
+ # the target class is eager loaded, we are not doing it.
24
+ # This would have the effect of loading all the models because they
25
+ # are likely to be related to each other. So we don't know the type
26
+ # of the primary key of the target.
22
27
  owner_klass.field(foreign_key, :index => options[:index])
23
28
  owner_klass.validates(target_name, options[:validates]) if options[:validates]
24
29
 
@@ -57,8 +57,8 @@ module NoBrainer::Document::Association::Core
57
57
 
58
58
  def assert_target_type(value)
59
59
  unless value.is_a?(target_klass) || value.nil?
60
- msg = "Trying to use a #{value.class} as a #{target_name}"
61
- raise NoBrainer::Error::InvalidType.new(msg)
60
+ options = { :attr_name => target_name, :value => value, :type => target_klass }
61
+ raise NoBrainer::Error::InvalidType.new(options)
62
62
  end
63
63
  end
64
64
  end
@@ -39,7 +39,7 @@ class NoBrainer::Document::Association::HasMany
39
39
 
40
40
  def target_criteria
41
41
  @target_criteria ||= target_klass.where(foreign_key => owner.id)
42
- ._after_instantiate(set_inverse_proc)
42
+ .after_find(set_inverse_proc)
43
43
  end
44
44
 
45
45
  def read
@@ -1,5 +1,5 @@
1
1
  module NoBrainer::Document::Attributes
2
- VALID_FIELD_OPTIONS = [:index, :default, :type, :validates]
2
+ VALID_FIELD_OPTIONS = [:index, :default, :type, :type_cast_method, :validates]
3
3
  RESERVED_FIELD_NAMES = [:index, :default, :and, :or, :selector, :associations] + NoBrainer::DecoratedSymbol::MODIFIERS.keys
4
4
  extend ActiveSupport::Concern
5
5
 
@@ -16,7 +16,7 @@ module NoBrainer::Document::Attributes
16
16
  end
17
17
 
18
18
  def attributes
19
- @_attributes.dup.freeze
19
+ Hash[@_attributes.keys.map { |k| [k, read_attribute(k)] }].with_indifferent_access.freeze
20
20
  end
21
21
 
22
22
  def read_attribute(name)
@@ -96,19 +96,6 @@ module NoBrainer::Document::Attributes
96
96
  RUBY
97
97
  end
98
98
 
99
- def remove_field(name)
100
- name = name.to_sym
101
-
102
- ([self] + descendants).each do |klass|
103
- klass.fields.delete(name)
104
- end
105
-
106
- inject_in_layer :attributes, <<-RUBY, __FILE__, __LINE__ + 1
107
- undef #{name}=
108
- undef #{name}
109
- RUBY
110
- end
111
-
112
99
  def has_field?(name)
113
100
  !!fields[name.to_sym]
114
101
  end
@@ -4,6 +4,7 @@ module NoBrainer::Document::Callbacks
4
4
  included do
5
5
  extend ActiveModel::Callbacks
6
6
  define_model_callbacks :initialize, :create, :update, :save, :destroy, :terminator => 'false'
7
+ define_model_callbacks :find, :only => [:after], :terminator => 'false'
7
8
  end
8
9
 
9
10
  def initialize(*args)
@@ -22,6 +23,10 @@ module NoBrainer::Document::Callbacks
22
23
  run_callbacks(:update) { super }
23
24
  end
24
25
 
26
+ def _update_changed(*args)
27
+ run_callbacks(:update) { super }
28
+ end
29
+
25
30
  def save(*args)
26
31
  run_callbacks(:save) { super }
27
32
  end
@@ -17,12 +17,6 @@ module NoBrainer::Document::Dirty
17
17
  @old_attributes_values.try(:clear)
18
18
  end
19
19
 
20
- def attributes
21
- # If we leak all the attributes (rare), we perform a copy to ensure that we
22
- # don't have issues with modified hashes/array. Devs are crazy.
23
- super.tap { |attrs| @old_attributes_values = attrs.deep_dup }
24
- end
25
-
26
20
  def _assign_attributes(attrs, options={})
27
21
  super
28
22
  clear_dirtiness if options[:from_db]
@@ -87,17 +81,5 @@ module NoBrainer::Document::Dirty
87
81
  end
88
82
  end
89
83
  end
90
-
91
- def remove_field(name)
92
- super
93
-
94
- inject_in_layer :dirty_tracking, <<-RUBY, __FILE__, __LINE__ + 1
95
- undef #{name}_changed?
96
- undef #{name}_change
97
- undef #{name}_was
98
- undef #{name}
99
- undef #{name}=
100
- RUBY
101
- end
102
84
  end
103
85
  end
@@ -6,7 +6,7 @@ module NoBrainer::Document::Id
6
6
  extend ActiveSupport::Concern
7
7
 
8
8
  included do
9
- self.field :id, :default => ->{ NoBrainer::Document::Id.generate }
9
+ self.field :id, :type => String, :default => ->{ NoBrainer::Document::Id.generate }
10
10
  end
11
11
 
12
12
  def ==(other)
@@ -59,11 +59,6 @@ module NoBrainer::Document::Index
59
59
  end
60
60
  end
61
61
 
62
- def remove_field(name)
63
- remove_index(name) if fields[name.to_sym][:index]
64
- super
65
- end
66
-
67
62
  def perform_create_index(index_name, options={})
68
63
  index_name = index_name.to_sym
69
64
  index_args = self.indexes[index_name]
@@ -31,37 +31,50 @@ module NoBrainer::Document::Persistance
31
31
  end
32
32
 
33
33
  def _create(options={})
34
- if options[:validate] && !valid?
35
- false
36
- else
37
- keys = self.class.insert_all(attributes)
38
- self.id ||= keys.first
39
- @new_record = false
40
- true
41
- end
34
+ return false if options[:validate] && !valid?
35
+ keys = self.class.insert_all(@_attributes)
36
+ self.id ||= keys.first
37
+ @new_record = false
38
+ true
42
39
  end
43
40
 
44
41
  def update(options={}, &block)
45
- if options[:validate] && !valid?
46
- false
47
- else
48
- selector.update_all(&block)
49
- true
50
- end
42
+ return false if options[:validate] && !valid?
43
+ selector.update_all(&block)
44
+ true
51
45
  end
52
46
 
53
47
  def replace(options={}, &block)
54
- if options[:validate] && !valid?
55
- false
48
+ return false if options[:validate] && !valid?
49
+ selector.replace_all(&block)
50
+ true
51
+ end
52
+
53
+ def _update_changed_attributes(changed_attrs)
54
+ # If we have a hash to save, we replace the entire document
55
+ # instead of doing some smart update. This is because RethinkDB
56
+ # will merge the existing hash with the given hash. If the
57
+ # user has deleted some keys, we won't remove them.
58
+ if changed_attrs.values.any? { |v| v.is_a?(Hash) }
59
+ selector.replace_all { @_attributes }
56
60
  else
57
- selector.replace_all(&block)
58
- true
61
+ selector.update_all { changed_attrs }
59
62
  end
60
63
  end
61
64
 
65
+ def _update_changed(options={})
66
+ return false if options[:validate] && !valid?
67
+
68
+ # We won't be using the `changes` values, because they went through
69
+ # read_attribute(), and we want the raw values.
70
+ changed_attrs = Hash[self.changed.map { |k| [k, @_attributes[k]] }]
71
+ _update_changed_attributes(changed_attrs) if changed_attrs.present?
72
+ true
73
+ end
74
+
62
75
  def save(options={})
63
76
  options = options.reverse_merge(:validate => true)
64
- new_record? ? _create(options) : replace(options) { attributes }
77
+ new_record? ? _create(options) : _update_changed(options)
65
78
  end
66
79
 
67
80
  def save!(*args)
@@ -3,7 +3,6 @@ module NoBrainer::Document::Serialization
3
3
 
4
4
  include ActiveModel::Serialization
5
5
  include ActiveModel::Serializers::JSON
6
- include ActiveModel::Serializers::Xml
7
6
 
8
7
  included { self.include_root_in_json = false }
9
8
  end
@@ -2,20 +2,18 @@ module NoBrainer::Document::Timestamps
2
2
  extend ActiveSupport::Concern
3
3
 
4
4
  included do
5
- class_attribute :timestamps_disabled
5
+ field :created_at, :type => Time
6
+ field :updated_at, :type => Time
6
7
 
7
- self.field :created_at, :type => Time
8
- self.field :updated_at, :type => Time
9
-
10
- before_create { self.created_at = Time.now unless self.timestamps_disabled }
11
- before_save { self.updated_at = Time.now unless self.timestamps_disabled }
8
+ before_create { self.created_at = self.updated_at = Time.now }
9
+ # Not using the before_update callback as it would mess
10
+ # with the dirty tracking. We want to bypass the database
11
+ # call if nothing has changed.
12
12
  end
13
13
 
14
- module ClassMethods
15
- def disable_timestamps
16
- self.timestamps_disabled = true
17
- self.remove_field :created_at
18
- self.remove_field :updated_at
19
- end
14
+ def _update_changed_attributes(changed_attrs)
15
+ self.updated_at = Time.now
16
+ changed_attrs['updated_at'] = @_attributes['updated_at']
17
+ super
20
18
  end
21
19
  end
@@ -3,6 +3,7 @@ module NoBrainer::Document::Types
3
3
 
4
4
  module CastingRules
5
5
  extend self
6
+ InvalidType = NoBrainer::Error::InvalidType
6
7
 
7
8
  def String(value)
8
9
  case value
@@ -64,9 +65,9 @@ module NoBrainer::Document::Types
64
65
  proc { raise InvalidType }
65
66
  end
66
67
 
67
- def cast(value, type, cast_method)
68
+ def cast(value, type, type_cast_method)
68
69
  return value if value.nil? || type.nil? || value.is_a?(type)
69
- cast_method.call(value)
70
+ type_cast_method.call(value)
70
71
  end
71
72
  end
72
73
 
@@ -83,39 +84,41 @@ module NoBrainer::Document::Types
83
84
  before_validation :add_type_errors
84
85
  end
85
86
 
86
- class InvalidType < RuntimeError
87
- attr_accessor :type
88
- def initialize(type=nil)
89
- @type = type
90
- end
91
-
92
- def validation_error_args
93
- [:invalid_type, :type => type.to_s.underscore.humanize.downcase]
94
- end
95
- end
96
-
97
87
  def add_type_errors
98
88
  return unless @pending_type_errors
99
89
  @pending_type_errors.each do |name, error|
100
- errors.add(name, *error.validation_error_args)
90
+ errors.add(name, :invalid_type, :type => error.human_type_name)
101
91
  end
102
92
  end
103
93
 
104
94
  module ClassMethods
95
+ def cast_value_for(name, value)
96
+ name = name.to_sym
97
+ field_def = fields[name]
98
+ return value unless field_def && field_def[:type]
99
+ NoBrainer::Document::Types::CastingRules.cast(value, field_def[:type], field_def[:type_cast_method])
100
+ rescue NoBrainer::Error::InvalidType => error
101
+ error.type = field_def[:type]
102
+ error.value = value
103
+ error.attr_name = name
104
+ raise error
105
+ end
106
+
105
107
  def field(name, options={})
106
- super
107
- return unless options.has_key?(:type)
108
+ return super unless options.has_key?(:type)
109
+
108
110
  name = name.to_sym
109
111
  type = options[:type]
110
- cast_method = NoBrainer::Document::Types::CastingRules.lookup(type)
112
+ options[:type_cast_method] = NoBrainer::Document::Types::CastingRules.lookup(type)
113
+
114
+ super
111
115
 
112
116
  inject_in_layer :types do
113
117
  define_method("#{name}=") do |value|
114
118
  begin
115
- value = NoBrainer::Document::Types::CastingRules.cast(value, type, cast_method)
119
+ value = self.class.cast_value_for(name, value)
116
120
  @pending_type_errors.try(:delete, name)
117
- rescue NoBrainer::Document::Types::InvalidType => error
118
- error.type ||= type
121
+ rescue NoBrainer::Error::InvalidType => error
119
122
  @pending_type_errors ||= {}
120
123
  @pending_type_errors[name] = error
121
124
  end
@@ -125,13 +128,5 @@ module NoBrainer::Document::Types
125
128
  define_method("#{name}?") { !!read_attribute(name) } if type == Boolean
126
129
  end
127
130
  end
128
-
129
- def remove_field(name)
130
- super
131
- # TODO remove the name? if we added it. Low priority though.
132
- inject_in_layer :types, <<-RUBY, __FILE__, __LINE__ + 1
133
- undef #{name}=
134
- RUBY
135
- end
136
131
  end
137
132
  end
@@ -0,0 +1,6 @@
1
+ module NoBrainer::DocumentWithTimestamps
2
+ extend ActiveSupport::Concern
3
+
4
+ include NoBrainer::Document
5
+ include NoBrainer::Document::Timestamps
6
+ end
@@ -1,11 +1,28 @@
1
1
  module NoBrainer::Error
2
- class Connection < StandardError; end
3
- class DocumentNotFound < StandardError; end
4
- class DocumentInvalid < StandardError; end
5
- class DocumentNotSaved < StandardError; end
6
- class ChildrenExist < StandardError; end
7
- class CannotUseIndex < StandardError; end
8
- class MissingIndex < StandardError; end
9
- class InvalidType < StandardError; end
10
- class AssociationNotSaved < StandardError; end
2
+ class Connection < RuntimeError; end
3
+ class DocumentNotFound < RuntimeError; end
4
+ class DocumentInvalid < RuntimeError; end
5
+ class DocumentNotSaved < RuntimeError; end
6
+ class ChildrenExist < RuntimeError; end
7
+ class CannotUseIndex < RuntimeError; end
8
+ class MissingIndex < RuntimeError; end
9
+ class InvalidType < RuntimeError; end
10
+ class AssociationNotSaved < RuntimeError; end
11
+
12
+ class InvalidType < RuntimeError
13
+ attr_accessor :attr_name, :value, :type
14
+ def initialize(options={})
15
+ @attr_name = options[:attr_name]
16
+ @value = options[:value]
17
+ @type = options[:type]
18
+ end
19
+
20
+ def human_type_name
21
+ type.to_s.underscore.humanize.downcase
22
+ end
23
+
24
+ def message
25
+ "#{attr_name} should be used with a #{human_type_name}. Got `#{value}`"
26
+ end
27
+ end
11
28
  end
@@ -3,7 +3,7 @@ class NoBrainer::QueryRunner::MissingIndex < NoBrainer::QueryRunner::Middleware
3
3
  @runner.call(env)
4
4
  rescue RethinkDB::RqlRuntimeError => e
5
5
  if e.message =~ /^Index `(.+)` was not found\.$/
6
- raise NoBrainer::Error::MissingIndex.new("Please run \"rake db:update_indexes\" to create index `#{$1}`\n" +
6
+ raise NoBrainer::Error::MissingIndex.new("Please run \"rake db:update_indexes\" to create the index `#{$1}`\n" +
7
7
  "--> Read http://nobrainer.io/docs/indexes for more information.")
8
8
  end
9
9
  raise
@@ -7,12 +7,22 @@ class NoBrainer::Railtie < Rails::Railtie
7
7
  config.action_dispatch.rescue_responses.merge!(
8
8
  "NoBrainer::Errors::DocumentNotFound" => :not_found,
9
9
  "NoBrainer::Errors::DocumentInvalid" => :unprocessable_entity,
10
+ "NoBrainer::Errors::InvalidType" => :bad_request,
10
11
  )
11
12
 
12
13
  rake_tasks do
13
14
  load "no_brainer/railtie/database.rake"
14
15
  end
15
16
 
17
+ console do
18
+ # Send console messages to standard error like ActiveRecord.
19
+ # Not the cleanest behavior, but if ActiveRecord does it, why not.
20
+ unless defined?(ActiveRecord)
21
+ console = ActiveSupport::Logger.new(STDERR)
22
+ Rails.logger.extend ActiveSupport::Logger.broadcast(console)
23
+ end
24
+ end
25
+
16
26
  config.after_initialize do
17
27
  NoBrainer::Config.configure unless NoBrainer::Config.configured?
18
28
 
data/lib/nobrainer.rb CHANGED
@@ -3,8 +3,8 @@ if Gem::Version.new(RUBY_VERSION.dup) < Gem::Version.new('1.9')
3
3
  end
4
4
 
5
5
  require 'active_support'
6
- %w(module/delegation module/attribute_accessors class/attribute object/blank object/inclusion
7
- object/deep_dup object/try hash/keys hash/indifferent_access hash/reverse_merge array/extract_options)
6
+ %w(module/delegation module/attribute_accessors class/attribute object/blank object/inclusion object/deep_dup
7
+ object/try hash/keys hash/indifferent_access hash/reverse_merge hash/deep_merge array/extract_options)
8
8
  .each { |dep| require "active_support/core_ext/#{dep}" }
9
9
 
10
10
  module NoBrainer
@@ -12,7 +12,7 @@ module NoBrainer
12
12
  extend NoBrainer::Autoload
13
13
 
14
14
  # We eager load things that could be loaded for the first time during the web request
15
- autoload :Document, :IndexManager, :Loader, :Fork, :DecoratedSymbol
15
+ autoload :Document, :DocumentWithTimestamps, :IndexManager, :Loader, :Fork, :DecoratedSymbol
16
16
  eager_autoload :Config, :Connection, :Error, :QueryRunner, :Criteria, :Util
17
17
 
18
18
  class << self
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: nobrainer
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.11.0
4
+ version: 0.12.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Nicolas Viennot
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2014-01-08 00:00:00.000000000 Z
11
+ date: 2014-01-09 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: rethinkdb
@@ -65,76 +65,78 @@ executables: []
65
65
  extensions: []
66
66
  extra_rdoc_files: []
67
67
  files:
68
- - lib/no_brainer/document/id.rb
69
- - lib/no_brainer/document/association/has_many.rb
70
68
  - lib/no_brainer/document/association/has_one.rb
71
69
  - lib/no_brainer/document/association/has_one_through.rb
72
70
  - lib/no_brainer/document/association/has_many_through.rb
73
- - lib/no_brainer/document/association/core.rb
74
- - lib/no_brainer/document/association/belongs_to.rb
71
+ - lib/no_brainer/document/association/has_many.rb
75
72
  - lib/no_brainer/document/association/eager_loader.rb
73
+ - lib/no_brainer/document/association/belongs_to.rb
74
+ - lib/no_brainer/document/association/core.rb
76
75
  - lib/no_brainer/document/polymorphic.rb
77
76
  - lib/no_brainer/document/store_in.rb
78
77
  - lib/no_brainer/document/injection_layer.rb
79
- - lib/no_brainer/document/index.rb
78
+ - lib/no_brainer/document/core.rb
79
+ - lib/no_brainer/document/criteria.rb
80
+ - lib/no_brainer/document/dynamic_attributes.rb
80
81
  - lib/no_brainer/document/serialization.rb
81
82
  - lib/no_brainer/document/association.rb
82
- - lib/no_brainer/document/timestamps.rb
83
- - lib/no_brainer/document/core.rb
84
- - lib/no_brainer/document/callbacks.rb
83
+ - lib/no_brainer/document/index.rb
85
84
  - lib/no_brainer/document/validation.rb
85
+ - lib/no_brainer/document/callbacks.rb
86
86
  - lib/no_brainer/document/dirty.rb
87
- - lib/no_brainer/document/attributes.rb
88
- - lib/no_brainer/document/dynamic_attributes.rb
89
87
  - lib/no_brainer/document/persistance.rb
90
- - lib/no_brainer/document/criteria.rb
88
+ - lib/no_brainer/document/timestamps.rb
89
+ - lib/no_brainer/document/attributes.rb
90
+ - lib/no_brainer/document/id.rb
91
91
  - lib/no_brainer/document/types.rb
92
92
  - lib/no_brainer/query_runner/connection.rb
93
93
  - lib/no_brainer/query_runner/database_on_demand.rb
94
94
  - lib/no_brainer/query_runner/table_on_demand.rb
95
95
  - lib/no_brainer/query_runner/write_error.rb
96
96
  - lib/no_brainer/query_runner/driver.rb
97
- - lib/no_brainer/query_runner/missing_index.rb
98
97
  - lib/no_brainer/query_runner/run_options.rb
99
98
  - lib/no_brainer/query_runner/logger.rb
99
+ - lib/no_brainer/query_runner/missing_index.rb
100
100
  - lib/no_brainer/railtie/database.rake
101
- - lib/no_brainer/criteria/chainable/limit.rb
102
- - lib/no_brainer/criteria/chainable/order_by.rb
103
- - lib/no_brainer/criteria/chainable/scope.rb
104
- - lib/no_brainer/criteria/chainable/raw.rb
105
- - lib/no_brainer/criteria/chainable/core.rb
106
- - lib/no_brainer/criteria/chainable/where.rb
107
- - lib/no_brainer/criteria/termination/inc.rb
108
- - lib/no_brainer/criteria/termination/count.rb
109
- - lib/no_brainer/criteria/termination/first.rb
110
- - lib/no_brainer/criteria/termination/enumerable.rb
111
- - lib/no_brainer/criteria/termination/update.rb
112
- - lib/no_brainer/criteria/termination/delete.rb
113
- - lib/no_brainer/criteria/termination/cache.rb
114
- - lib/no_brainer/criteria/termination/preload.rb
115
- - lib/no_brainer/decorated_symbol.rb
116
101
  - lib/no_brainer/index_manager.rb
117
102
  - lib/no_brainer/loader.rb
118
103
  - lib/no_brainer/locale/en.yml
119
104
  - lib/no_brainer/fork.rb
120
105
  - lib/no_brainer/connection.rb
121
106
  - lib/no_brainer/query_runner.rb
122
- - lib/no_brainer/error.rb
123
- - lib/no_brainer/railtie.rb
124
107
  - lib/no_brainer/config.rb
125
108
  - lib/no_brainer/autoload.rb
126
- - lib/no_brainer/document.rb
127
109
  - lib/no_brainer/util.rb
110
+ - lib/no_brainer/document.rb
111
+ - lib/no_brainer/document_with_timestamps.rb
112
+ - lib/no_brainer/decorated_symbol.rb
113
+ - lib/no_brainer/criteria/update.rb
114
+ - lib/no_brainer/criteria/scope.rb
115
+ - lib/no_brainer/criteria/raw.rb
116
+ - lib/no_brainer/criteria/preload.rb
117
+ - lib/no_brainer/criteria/order_by.rb
118
+ - lib/no_brainer/criteria/limit.rb
119
+ - lib/no_brainer/criteria/inc.rb
120
+ - lib/no_brainer/criteria/first.rb
121
+ - lib/no_brainer/criteria/enumerable.rb
122
+ - lib/no_brainer/criteria/delete.rb
123
+ - lib/no_brainer/criteria/count.rb
124
+ - lib/no_brainer/criteria/core.rb
125
+ - lib/no_brainer/criteria/cache.rb
126
+ - lib/no_brainer/criteria/after_find.rb
127
+ - lib/no_brainer/criteria/where.rb
128
128
  - lib/no_brainer/criteria.rb
129
+ - lib/no_brainer/error.rb
130
+ - lib/no_brainer/railtie.rb
129
131
  - lib/rails/generators/nobrainer.rb
130
132
  - lib/rails/generators/nobrainer/model/model_generator.rb
131
133
  - lib/rails/generators/nobrainer/model/templates/model.rb.tt
132
134
  - lib/nobrainer.rb
133
135
  - README.md
134
- - LICENSE.md
135
- homepage: http://github.com/nviennot/nobrainer
136
+ - LICENSE
137
+ homepage: http://nobrainer.io
136
138
  licenses:
137
- - MIT
139
+ - LGPLv3
138
140
  metadata: {}
139
141
  post_install_message:
140
142
  rdoc_options: []
data/LICENSE.md DELETED
@@ -1,7 +0,0 @@
1
- Copyright (C) 2012 Nicolas Viennot
2
-
3
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
-
5
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
-
7
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -1,33 +0,0 @@
1
- module NoBrainer::Criteria::Chainable::Raw
2
- extend ActiveSupport::Concern
3
-
4
- included { attr_accessor :_raw, :__after_instantiate }
5
-
6
- def raw
7
- chain { |criteria| criteria._raw = true }
8
- end
9
-
10
- def _after_instantiate(block)
11
- # Just some helper for the has_many association to set the inverses on the
12
- # related belongs_to. A bit hackish.
13
- chain { |criteria| criteria.__after_instantiate = block }
14
- end
15
-
16
- def merge!(criteria, options={})
17
- super
18
- self._raw = criteria._raw unless criteria._raw.nil?
19
- self.__after_instantiate ||= criteria.__after_instantiate
20
- self
21
- end
22
-
23
- private
24
-
25
- def raw?
26
- !!_raw
27
- end
28
-
29
- def instantiate_doc(attrs)
30
- (raw? ? attrs : klass.new_from_db(attrs))
31
- .tap { |doc| __after_instantiate.call(doc) if __after_instantiate }
32
- end
33
- end