thefool808-couch_potato 0.2.7

Sign up to get free protection for your applications and to get access to all the features.
Files changed (42) hide show
  1. data/MIT-LICENSE.txt +19 -0
  2. data/README.md +269 -0
  3. data/VERSION.yml +4 -0
  4. data/init.rb +3 -0
  5. data/lib/core_ext/date.rb +10 -0
  6. data/lib/core_ext/object.rb +5 -0
  7. data/lib/core_ext/string.rb +15 -0
  8. data/lib/core_ext/time.rb +11 -0
  9. data/lib/couch_potato.rb +41 -0
  10. data/lib/couch_potato/database.rb +96 -0
  11. data/lib/couch_potato/persistence.rb +94 -0
  12. data/lib/couch_potato/persistence/belongs_to_property.rb +58 -0
  13. data/lib/couch_potato/persistence/callbacks.rb +96 -0
  14. data/lib/couch_potato/persistence/dirty_attributes.rb +27 -0
  15. data/lib/couch_potato/persistence/json.rb +45 -0
  16. data/lib/couch_potato/persistence/magic_timestamps.rb +13 -0
  17. data/lib/couch_potato/persistence/properties.rb +56 -0
  18. data/lib/couch_potato/persistence/simple_property.rb +77 -0
  19. data/lib/couch_potato/view/base_view_spec.rb +24 -0
  20. data/lib/couch_potato/view/custom_view_spec.rb +27 -0
  21. data/lib/couch_potato/view/custom_views.rb +44 -0
  22. data/lib/couch_potato/view/model_view_spec.rb +63 -0
  23. data/lib/couch_potato/view/properties_view_spec.rb +39 -0
  24. data/lib/couch_potato/view/raw_view_spec.rb +25 -0
  25. data/lib/couch_potato/view/view_query.rb +44 -0
  26. data/rails/init.rb +7 -0
  27. data/spec/callbacks_spec.rb +271 -0
  28. data/spec/create_spec.rb +22 -0
  29. data/spec/custom_view_spec.rb +134 -0
  30. data/spec/destroy_spec.rb +29 -0
  31. data/spec/property_spec.rb +64 -0
  32. data/spec/spec.opts +4 -0
  33. data/spec/spec_helper.rb +31 -0
  34. data/spec/unit/attributes_spec.rb +26 -0
  35. data/spec/unit/create_spec.rb +58 -0
  36. data/spec/unit/customs_views_spec.rb +15 -0
  37. data/spec/unit/database_spec.rb +18 -0
  38. data/spec/unit/dirty_attributes_spec.rb +113 -0
  39. data/spec/unit/string_spec.rb +13 -0
  40. data/spec/unit/view_query_spec.rb +9 -0
  41. data/spec/update_spec.rb +40 -0
  42. metadata +135 -0
data/MIT-LICENSE.txt ADDED
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2007 Bryan Helmkamp, Seth Fitzsimmons
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,269 @@
1
+ ## Couch Potato
2
+
3
+ ... is a persistence layer written in ruby for CouchDB.
4
+
5
+ ### Mission
6
+
7
+ The goal of Couch Potato is to create a minimal framework in order to store and retrieve Ruby objects to/from CouchDB and create and query views.
8
+
9
+ It follows the document/view/querying semantics established by CouchDB and won't try to mimic ActiveRecord behavior in any way as that IS BAD.
10
+
11
+ Code that uses Couch Potato should be easy to test.
12
+
13
+ Lastly Couch Potato aims to provide a seamless integration with Ruby on Rails, e.g. routing, form helpers etc.
14
+
15
+ ### Core Features
16
+
17
+ * persisting objects by including the CouchPotato::Persistence module
18
+ * declarative views with either custom or generated map/reduce functions
19
+ * extensive spec suite
20
+
21
+ ### Installation
22
+
23
+ Couch Potato is hosted as a gem on github which you can install like this:
24
+
25
+ sudo gem source --add http://gems.github.com # if you haven't already
26
+ sudo gem install langalex-couch_potato
27
+
28
+ #### Using with your ruby application:
29
+
30
+ require 'rubygems'
31
+ gem 'langalex-couch_potato'
32
+ require 'couch_potato'
33
+
34
+ Alternatively you can download or clone the source repository and then require lib/couch_potato.rb.
35
+
36
+ You MUST specificy the name of the database:
37
+
38
+ CouchPotato::Config.database_name = 'name of the db'
39
+
40
+ The server URL will default to http://localhost:5984/ unless specified with:
41
+
42
+ CouchPotato::Config.database_server = "http://example.com:5984/"
43
+
44
+ #### Using with Rails
45
+
46
+ Add to your config/environment.rb:
47
+
48
+ config.gem 'langalex-couch_potato', :lib => 'couch_potato', :source => 'http://gems.github.com'
49
+
50
+ Then create a config/couchdb.yml:
51
+
52
+ development: development_db_name
53
+ test: test_db_name
54
+ production: http://db.server/production_db_name
55
+
56
+ Alternatively you can also install Couch Potato directly as a plugin.
57
+
58
+ ### Introduction
59
+
60
+ This is a basic tutorial on how to use Couch Potato. If you want to know all the details feel free to read the specs.
61
+
62
+ #### Save, load objects
63
+
64
+ First you need a class.
65
+
66
+ class User
67
+ end
68
+
69
+ To make instances of this class persistent include the persistence module:
70
+
71
+ class User
72
+ include CouchPotato::Persistence
73
+ end
74
+
75
+ If you want to store any properties you have to declare them:
76
+
77
+ class User
78
+ include CouchPotato::Persistence
79
+
80
+ property :name
81
+ end
82
+
83
+ Properties can be of any type:
84
+
85
+ class User
86
+ include CouchPotato::Persistence
87
+
88
+ property :address, :type => Address
89
+ end
90
+
91
+ Now you can save your objects. All database operations are encapsulated in the CouchPotato::Database class. This separates your domain logic from the database access logic which makes it easier to write tests and also keeps you models smaller and cleaner.
92
+
93
+ user = User.new :name => 'joe'
94
+ CouchPotato.database.save_document user # or save_document!
95
+
96
+ You can of course also retrieve your instance:
97
+
98
+ CouchPotato.database.load_document "id_of_the_user_document" # => <#User 0x3075>
99
+
100
+
101
+ #### Properties
102
+
103
+ You can access the properties you declared above through normal attribute accessors.
104
+
105
+ user.name # => 'joe'
106
+ user.name = {:first => ['joe', 'joey'], :last => 'doe', :middle => 'J'} # you can set any ruby object that responds_to :to_json (includes all core objects)
107
+ user._id # => "02097f33a0046123f1ebc0ebb6937269"
108
+ user._rev # => "2769180384"
109
+ user.created_at # => Fri Oct 24 19:05:54 +0200 2008
110
+ user.updated_at # => Fri Oct 24 19:05:54 +0200 2008
111
+ user.new? # => false
112
+
113
+ If you want to have properties that don't map to any JSON type, i.e. other than String, Number, Boolean, Hash or Array you have to define the type like this:
114
+
115
+ class User
116
+ property :date_of_birth, :type => Date
117
+ end
118
+
119
+ The date_of_birth property is now automatically serialized to JSON and back when storing/retrieving objects.
120
+
121
+ #### Dirty tracking
122
+
123
+ CouchPotato tracks the dirty state of attributes in the same way ActiveRecord does:
124
+
125
+ user = User.create :name => 'joe'
126
+ user.name # => 'joe'
127
+ user.name_changed? # => false
128
+ user.name_was # => nil
129
+
130
+ You can also force a dirty state:
131
+
132
+ user.name = 'jane'
133
+ user.name_changed? # => true
134
+ user.name_not_changed
135
+ user.name_changed? # => false
136
+ CouchPotato.database.save_document user # does nothing as no attributes are dirty
137
+
138
+
139
+ #### Object validations
140
+
141
+ Couch Potato uses the validatable library for vaidation (http://validatable.rubyforge.org/)\
142
+
143
+ class User
144
+ property :name
145
+ validates_presence_of :name
146
+ end
147
+
148
+ user = User.new
149
+ user.valid? # => false
150
+ user.errors.on(:name) # => [:name, 'can't be blank']
151
+
152
+ #### Finding stuff
153
+
154
+ In order to find data in your CouchDB you have to create a view first. Couch Potato offers you to create and manage those views for you. All you have to do is declare them in your classes:
155
+
156
+ class User
157
+ include CouchPotato::Persistence
158
+ property :name
159
+
160
+ view :all, :key => :created_at
161
+ end
162
+
163
+ This will create a view called "all" in the "user" design document with a map function that emits "created_at" for every user document.
164
+
165
+ CouchPotato.database.view User.all
166
+
167
+ This will load all user documents in your database sorted by created_at.
168
+
169
+ CouchPotato.database.view User.all(:key => (Time.now- 10)..(Time.now), :descending => true)
170
+
171
+ Any options you pass in will be passed onto CouchDB.
172
+
173
+ Composite keys are also possible:
174
+
175
+ class User
176
+ property :name
177
+
178
+ view :all, :key => [:created_at, :name]
179
+ end
180
+
181
+ The creation of views is based on view specification classes (see the CouchPotato::View module). The above code uses the ModelViewSpec class which is used to find models by their properties. For more sophisticated searches you can use other view specifications (either use the built-in or provide your own) by passing a type parameter:
182
+
183
+ If you have larger structures and you only want to load some attributes you can use the PropertiesViewSpec (the full class name is automatically derived):
184
+
185
+ class User
186
+ property :name
187
+ property :bio
188
+
189
+ view :all, :key => :created_at, :properties => [:name], :type => :properties
190
+ end
191
+
192
+ CouchPotato.database.view(User.everyone).first.name # => "joe"
193
+ CouchPotato.database.view(User.everyone).first.bio # => nil
194
+
195
+ You can also pass in custom map/reduce functions with the custom view spec:
196
+
197
+ class User
198
+ view :all, :map => "function(doc) { emit(doc.created_at, null)}", :include_docs => true, :type => :custom
199
+ end
200
+
201
+ If you don't want the results to be converted into models the raw view is your friend:
202
+
203
+ class User
204
+ view :all, :map => "function(doc) { emit(doc.created_at, doc.name)}", :type => :raw
205
+ end
206
+
207
+ When querying this view you will get the raw data returned by CouchDB which looks something like this: {'total_entries': 2, 'rows': [{'value': 'alex', 'key': '2009-01-03 00:02:34 +000', 'id': '75976rgi7546gi02a'}]}
208
+
209
+ To process this raw data you can also pass in a results filter:
210
+
211
+ class User
212
+ view :all, :map => "function(doc) { emit(doc.created_at, doc.name)}", :type => :raw, :results_filter => lambda {|results| results['rows'].map{|row| row['value']}}
213
+ end
214
+
215
+ In this case querying the view would only return the emitted value for each row.
216
+
217
+ You can pass in your own view specifications by passing in :type => MyViewSpecClass. Take a look at the CouchPotato::View::*ViewSpec classes to get an idea of how this works.
218
+
219
+ #### Associations
220
+
221
+ Not supported. Not sure if they ever will be. You can implement those yourself using views and custom methods on your models.
222
+
223
+ #### Callbacks
224
+
225
+ Couch Potato supports the usual lifecycle callbacks known from ActiveRecord:
226
+
227
+ class User
228
+ include CouchPotato::Persistence
229
+
230
+ before_create :do_something_before_create
231
+ before_update {|user, db| user.do_something_on_update}
232
+ end
233
+
234
+ This will call the method do_something_before_create before creating an object and run the given lambda before updating one. Lambda callbacks get passed the model as their first argument. Optionally if a lambda declares two arguments it also gets passed the database object. This is useful for creating other objects or querying views. Method callbacks don't receive any arguments by default but will get passed the database if they declare an argument.
235
+
236
+ Supported callbacks are: :before_validation_on_create, :before_validation_on_update, :before_validation_on_save, :before_create, :after_create, :before_update, :after_update, :before_save, :after_save, :before_destroy, :after_destroy.
237
+
238
+ #### Testing
239
+
240
+ To make testing easier and faster database logic has been put into its own class, which you can replace and stub out in whatever way you want:
241
+
242
+ class User
243
+ include CouchPotato::Persistence
244
+ end
245
+
246
+ # RSpec
247
+ describe 'save a user' do
248
+ it 'should save' do
249
+ couchrest_db = stub 'couchrest_db',
250
+ database = CouchPotato::Database.new couchrest_db
251
+ user = User.new
252
+ couchrest_db.should_receive(:save_doc).with(...)
253
+ database.save_document user
254
+ end
255
+ end
256
+
257
+ By creating you own instances of CouchPotato::Database and passing them a fake CouchRest database instance you can completely disconnect your unit tests/spec from the database.
258
+
259
+ ### Helping out
260
+
261
+ Please fix bugs, add more specs, implement new features by forking the github repo at http://github.com/langalex/couch_potato.
262
+
263
+ You can run all the specs by calling 'rake spec_unit' and 'rake spec_functional' in the root folder of Couch Potato. The specs require a running CouchDB instance at http://localhost:5984
264
+
265
+ I will only accept patches that are covered by specs - sorry.
266
+
267
+ ### Contact
268
+
269
+ If you have any questions/suggestions etc. please contact me at alex at upstream-berlin.com or @langalex on twitter.
data/VERSION.yml ADDED
@@ -0,0 +1,4 @@
1
+ ---
2
+ :major: 0
3
+ :minor: 2
4
+ :patch: 7
data/init.rb ADDED
@@ -0,0 +1,3 @@
1
+ # this is for rails only
2
+
3
+ require File.dirname(__FILE__) + '/rails/init'
@@ -0,0 +1,10 @@
1
+ class Date
2
+ def to_json(*a)
3
+ %("#{strftime("%Y/%m/%d")}")
4
+ end
5
+
6
+ def self.json_create string
7
+ return nil if string.nil?
8
+ Date.parse(string)
9
+ end
10
+ end
@@ -0,0 +1,5 @@
1
+ Object.class_eval do
2
+ def try(method, *args)
3
+ self.send method, *args if self.respond_to?(method)
4
+ end
5
+ end
@@ -0,0 +1,15 @@
1
+ module ActiveSupportMethods
2
+ def camelize
3
+ sub(/^([a-z])/) {$1.upcase}.gsub(/_([a-z])/) do
4
+ $1.upcase
5
+ end
6
+ end
7
+
8
+ def underscore
9
+ gsub(/([A-Z])/) do
10
+ '_' + $1.downcase
11
+ end.sub(/^_/, '')
12
+ end
13
+ end
14
+
15
+ String.send :include, ActiveSupportMethods #unless String.new.respond_to?(:camelize)
@@ -0,0 +1,11 @@
1
+ class Time
2
+ def to_json(*a)
3
+ %("#{strftime("%Y/%m/%d %H:%M:%S +0000")}")
4
+ end
5
+
6
+ def self.json_create string
7
+ return nil if string.nil?
8
+ d = DateTime.parse(string).new_offset
9
+ self.utc(d.year, d.month, d.day, d.hour, d.min, d.sec)
10
+ end
11
+ end
@@ -0,0 +1,41 @@
1
+ require 'couchrest'
2
+ require 'json'
3
+ require 'json/add/core'
4
+ require 'json/add/rails'
5
+
6
+ require 'ostruct'
7
+
8
+ require 'validatable'
9
+
10
+
11
+ module CouchPotato
12
+ Config = OpenStruct.new
13
+
14
+ # Returns a database instance which you can then use to create objects and query views. You have to set the CouchPotato::Config.database_name before this works.
15
+ def self.database
16
+ @@__database ||= Database.new(self.couchrest_database)
17
+ end
18
+
19
+ # Returns the underlying CouchRest database object if you want low level access to your CouchDB. You have to set the CouchPotato::Config.database_name before this works.
20
+ def self.couchrest_database
21
+ @@__couchrest_database ||= CouchRest.database(full_url_to_database)
22
+ end
23
+
24
+ private
25
+
26
+ def self.full_url_to_database
27
+ raise('No Database configured. Set CouchPotato::Config.database_name') unless CouchPotato::Config.database_name
28
+ if CouchPotato::Config.database_server
29
+ return "#{CouchPotato::Config.database_server}#{CouchPotato::Config.database_name}"
30
+ else
31
+ return "http://localhost:5984/#{CouchPotato::Config.database_name}"
32
+ end
33
+ end
34
+ end
35
+
36
+ require File.dirname(__FILE__) + '/core_ext/object'
37
+ require File.dirname(__FILE__) + '/core_ext/time'
38
+ require File.dirname(__FILE__) + '/core_ext/date'
39
+ require File.dirname(__FILE__) + '/core_ext/string'
40
+ require File.dirname(__FILE__) + '/couch_potato/persistence'
41
+
@@ -0,0 +1,96 @@
1
+ module CouchPotato
2
+ class Database
3
+
4
+ class ValidationsFailedError < ::StandardError; end
5
+
6
+ def initialize(couchrest_database)
7
+ @database = couchrest_database
8
+ begin
9
+ couchrest_database.info
10
+ rescue RestClient::ResourceNotFound
11
+ raise "Database '#{couchrest_database.name}' does not exist."
12
+ end
13
+ end
14
+
15
+ def view(spec)
16
+ results = CouchPotato::View::ViewQuery.new(database,
17
+ spec.design_document, spec.view_name, spec.map_function,
18
+ spec.reduce_function).query_view!(spec.view_parameters)
19
+ spec.process_results results
20
+ end
21
+
22
+ def save_document(document)
23
+ return true unless document.dirty?
24
+ if document.new?
25
+ create_document document
26
+ else
27
+ update_document document
28
+ end
29
+ end
30
+ alias_method :save, :save_document
31
+
32
+ def save_document!(document)
33
+ save_document(document) || raise(ValidationsFailedError.new(document.errors.full_messages))
34
+ end
35
+ alias_method :save!, :save_document!
36
+
37
+ def destroy_document(document)
38
+ document.run_callbacks :before_destroy, self
39
+ document._deleted = true
40
+ database.delete_doc document.to_hash
41
+ document.run_callbacks :after_destroy, self
42
+ document._id = nil
43
+ document._rev = nil
44
+ end
45
+ alias_method :destroy, :destroy_document
46
+
47
+ def load_document(id)
48
+ raise "Can't load a document without an id (got nil)" if id.nil?
49
+ begin
50
+ json = database.get(id)
51
+ Class.const_get(json['ruby_class']).json_create json
52
+ rescue(RestClient::ResourceNotFound)
53
+ nil
54
+ end
55
+ end
56
+ alias_method :load, :load_document
57
+
58
+ def inspect
59
+ "#<CouchPotato::Database>"
60
+ end
61
+
62
+ private
63
+
64
+ def create_document(document)
65
+ document.run_callbacks :before_validation_on_save, self
66
+ document.run_callbacks :before_validation_on_create, self
67
+ return unless document.valid?
68
+ document.run_callbacks :before_save, self
69
+ document.run_callbacks :before_create, self
70
+ res = database.save_doc document.to_hash
71
+ document._rev = res['rev']
72
+ document._id = res['id']
73
+ document.run_callbacks :after_save, self
74
+ document.run_callbacks :after_create, self
75
+ true
76
+ end
77
+
78
+ def update_document(document)
79
+ document.run_callbacks :before_validation_on_save, self
80
+ document.run_callbacks :before_validation_on_update, self
81
+ return unless document.valid?
82
+ document.run_callbacks :before_save, self
83
+ document.run_callbacks :before_update, self
84
+ res = database.save_doc document.to_hash
85
+ document._rev = res['rev']
86
+ document.run_callbacks :after_save, self
87
+ document.run_callbacks :after_update, self
88
+ true
89
+ end
90
+
91
+ def database
92
+ @database
93
+ end
94
+
95
+ end
96
+ end