ampere 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
data/.document ADDED
@@ -0,0 +1,5 @@
1
+ lib/**/*.rb
2
+ bin/*
3
+ -
4
+ features/**/*.feature
5
+ LICENSE.txt
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --color
data/.rvmrc ADDED
@@ -0,0 +1 @@
1
+ rvm use 1.9.2@ampere
data/Gemfile ADDED
@@ -0,0 +1,18 @@
1
+ source "http://rubygems.org"
2
+ # Add dependencies required to use your gem here.
3
+ # Example:
4
+ # gem "activesupport", ">= 2.3.5"
5
+
6
+ gem 'redis'
7
+
8
+ # Add dependencies to develop your gem here.
9
+ # Include everything needed to run rake, tests, features, etc.
10
+ group :development do
11
+ gem "shoulda", ">= 0"
12
+ gem "cucumber", ">= 0"
13
+ gem "bundler", "~> 1.0.0"
14
+ gem "jeweler", "~> 1.6.4"
15
+ gem 'simplecov', :require => false, :group => :test
16
+ gem "rspec"
17
+ gem "rdoc"
18
+ end
data/Gemfile.lock ADDED
@@ -0,0 +1,51 @@
1
+ GEM
2
+ remote: http://rubygems.org/
3
+ specs:
4
+ builder (3.0.0)
5
+ cucumber (1.1.3)
6
+ builder (>= 2.1.2)
7
+ diff-lcs (>= 1.1.2)
8
+ gherkin (~> 2.6.7)
9
+ json (>= 1.4.6)
10
+ term-ansicolor (>= 1.0.6)
11
+ diff-lcs (1.1.3)
12
+ gherkin (2.6.8)
13
+ json (>= 1.4.6)
14
+ git (1.2.5)
15
+ jeweler (1.6.4)
16
+ bundler (~> 1.0)
17
+ git (>= 1.2.5)
18
+ rake
19
+ json (1.6.1)
20
+ multi_json (1.0.4)
21
+ rake (0.9.2.2)
22
+ rdoc (3.11)
23
+ json (~> 1.4)
24
+ redis (2.2.2)
25
+ rspec (2.7.0)
26
+ rspec-core (~> 2.7.0)
27
+ rspec-expectations (~> 2.7.0)
28
+ rspec-mocks (~> 2.7.0)
29
+ rspec-core (2.7.1)
30
+ rspec-expectations (2.7.0)
31
+ diff-lcs (~> 1.1.2)
32
+ rspec-mocks (2.7.0)
33
+ shoulda (2.11.3)
34
+ simplecov (0.5.4)
35
+ multi_json (~> 1.0.3)
36
+ simplecov-html (~> 0.5.3)
37
+ simplecov-html (0.5.3)
38
+ term-ansicolor (1.0.7)
39
+
40
+ PLATFORMS
41
+ ruby
42
+
43
+ DEPENDENCIES
44
+ bundler (~> 1.0.0)
45
+ cucumber
46
+ jeweler (~> 1.6.4)
47
+ rdoc
48
+ redis
49
+ rspec
50
+ shoulda
51
+ simplecov
data/LICENSE.txt ADDED
@@ -0,0 +1,70 @@
1
+ Copyright (c) 2011 Max Thom Stahl
2
+
3
+ THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
4
+
5
+ 1. DEFINITIONS
6
+
7
+ "Contribution" means:
8
+
9
+ a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and
10
+ b) in the case of each subsequent Contributor:
11
+ i) changes to the Program, and
12
+ ii) additions to the Program;
13
+ where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program.
14
+ "Contributor" means any person or entity that distributes the Program.
15
+
16
+ "Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.
17
+
18
+ "Program" means the Contributions distributed in accordance with this Agreement.
19
+
20
+ "Recipient" means anyone who receives the Program under this Agreement, including all Contributors.
21
+
22
+ 2. GRANT OF RIGHTS
23
+
24
+ a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form.
25
+ b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
26
+ c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program.
27
+ d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.
28
+ 3. REQUIREMENTS
29
+
30
+ A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:
31
+
32
+ a) it complies with the terms and conditions of this Agreement; and
33
+ b) its license agreement:
34
+ i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
35
+ ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;
36
+ iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and
37
+ iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange.
38
+ When the Program is made available in source code form:
39
+
40
+ a) it must be made available under this Agreement; and
41
+ b) a copy of this Agreement must be included with each copy of the Program.
42
+ Contributors may not remove or alter any copyright notices contained within the Program.
43
+
44
+ Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution.
45
+
46
+ 4. COMMERCIAL DISTRIBUTION
47
+
48
+ Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.
49
+
50
+ For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.
51
+
52
+ 5. NO WARRANTY
53
+
54
+ EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
55
+
56
+ 6. DISCLAIMER OF LIABILITY
57
+
58
+ EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
59
+
60
+ 7. GENERAL
61
+
62
+ If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
63
+
64
+ If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
65
+
66
+ All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
67
+
68
+ Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.
69
+
70
+ This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.
data/README.md ADDED
@@ -0,0 +1,89 @@
1
+ # Ampere — A Redis ORM for Ruby
2
+
3
+ Ampere is an ActiveRecord-style ORM for the Redis key/value data store.
4
+
5
+ This is under active development right now and not very far along. Stay
6
+ tuned for further developments.
7
+
8
+ ## Usage
9
+
10
+ Write a model class and make it inherit from the `Ampere::Model` class.
11
+ These work pretty similarly to how they do in ActiveRecord or Mongoid.
12
+
13
+ class Car < Ampere::Model
14
+ field :make
15
+ field :model
16
+ field :year
17
+
18
+ has_one :engine
19
+ has_many :passengers
20
+ end
21
+
22
+ class Engine < Ampere::Model
23
+ field :displacement
24
+ field :cylinders
25
+ field :configuration
26
+
27
+ belongs_to :car
28
+ end
29
+
30
+ class Passenger < Ampere::Model
31
+ field :name
32
+ field :seat
33
+
34
+ belongs_to :car
35
+ end
36
+
37
+ This will define attr accessors for each field. Then to instantiate it,
38
+
39
+ Post.new :title => "BREAKING: Kitties Are Awesome",
40
+ :contents => "This just in! Kitties are super adorable, and super great."
41
+
42
+ Later, when you want to retrieve it, you can use the where() method (although this will
43
+ be slower if one of the keys you are searching by isn't indexed).
44
+
45
+ post = Post.where(:title => "BREAKING: Kitties Are Awesome").first
46
+
47
+ ### Indexes
48
+
49
+ Indexes work similar to Mongoid. They are non-unique.
50
+
51
+ class Student < Ampere::Model
52
+ field :last_name
53
+ field :first_name
54
+
55
+ index :last_name
56
+ end
57
+
58
+ This will create an index of the last names of students, and lookups by
59
+ last_name will happen faster.
60
+
61
+ You can also define indices on multiple fields.
62
+
63
+ class Student < Ampere::Model
64
+ field :last_name
65
+ field :first_name
66
+
67
+ index [:last_name, :first_name]
68
+ end
69
+
70
+ Queries performed on compound indices will always run faster than queries on multiple
71
+ individual indices, which will always run faster than queries on unindexed fields.
72
+
73
+ _**Warning:**_ If you query on an un-indexed field, the returned result set will not be
74
+ evaluated lazily!
75
+
76
+ ## Contributing to ampere
77
+
78
+ * Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
79
+ * Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it
80
+ * Fork the project
81
+ * Start a feature/bugfix branch
82
+ * Commit and push until you are happy with your contribution
83
+ * Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
84
+ * 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.
85
+
86
+ ## Copyright
87
+
88
+ Copyright (c) 2011 Max Thom Stahl. See LICENSE.txt for further details.
89
+
data/Rakefile ADDED
@@ -0,0 +1,49 @@
1
+ # encoding: utf-8
2
+
3
+ require 'rubygems'
4
+ require 'bundler'
5
+ begin
6
+ Bundler.setup(:default, :development)
7
+ rescue Bundler::BundlerError => e
8
+ $stderr.puts e.message
9
+ $stderr.puts "Run `bundle install` to install missing gems"
10
+ exit e.status_code
11
+ end
12
+ require 'rake'
13
+
14
+ require 'jeweler'
15
+ Jeweler::Tasks.new do |gem|
16
+ # gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options
17
+ gem.name = "ampere"
18
+ gem.homepage = "http://github.com/mstahl/ampere"
19
+ gem.license = "EPL"
20
+ gem.summary = %Q{A pure Ruby ORM for Redis.}
21
+ gem.description = %Q{An ActiveRecord/Mongoid-esque object model for the Redis key/value data store.}
22
+ gem.email = "max@villainousindustri.es"
23
+ gem.authors = ["Max Thom Stahl"]
24
+ # dependencies defined in Gemfile
25
+ end
26
+ Jeweler::RubygemsDotOrgTasks.new
27
+
28
+ require 'rake/testtask'
29
+ Rake::TestTask.new(:test) do |test|
30
+ test.libs << 'lib' << 'test'
31
+ test.pattern = 'test/**/test_*.rb'
32
+ test.verbose = true
33
+ end
34
+
35
+ require 'cucumber/rake/task'
36
+ Cucumber::Rake::Task.new(:features)
37
+
38
+ task :default => :test
39
+
40
+ require 'rdoc/task'
41
+ # Rake::RDocTask.new do |rdoc|
42
+ RDoc::Task.new do |rdoc|
43
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
44
+
45
+ rdoc.rdoc_dir = 'rdoc'
46
+ rdoc.title = "ampere #{version}"
47
+ rdoc.rdoc_files.include('README*')
48
+ rdoc.rdoc_files.include('lib/**/*.rb')
49
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.1.0
@@ -0,0 +1,9 @@
1
+ Feature: something something
2
+ In order to something something
3
+ A user something something
4
+ something something something
5
+
6
+ Scenario: something something
7
+ Given inspiration
8
+ When I create a sweet new gem
9
+ Then everyone should see how awesome I am
File without changes
@@ -0,0 +1,15 @@
1
+ require 'bundler'
2
+ begin
3
+ Bundler.setup(:default, :development)
4
+ rescue Bundler::BundlerError => e
5
+ $stderr.puts e.message
6
+ $stderr.puts "Run `bundle install` to install missing gems"
7
+ exit e.status_code
8
+ end
9
+
10
+ $LOAD_PATH.unshift(File.dirname(__FILE__) + '/../../lib')
11
+ require 'ampere'
12
+
13
+ require 'test/unit/assertions'
14
+
15
+ World(Test::Unit::Assertions)
data/lib/ampere.rb ADDED
@@ -0,0 +1,26 @@
1
+ require "redis"
2
+ require "pp"
3
+
4
+ module Ampere
5
+ @@connection = nil
6
+
7
+ def self.connect(options = {})
8
+ @@connection = Redis.connect(options)
9
+ end
10
+
11
+ def self.disconnect
12
+ return unless connected?
13
+ @@connection.quit
14
+ @@connection = nil
15
+ end
16
+
17
+ def self.connected?
18
+ !! @@connection
19
+ end
20
+
21
+ def self.connection
22
+ @@connection
23
+ end
24
+ end
25
+
26
+ Dir[File.join(File.dirname(__FILE__), 'ampere', '**', '*.rb')].each {|f| require f}
@@ -0,0 +1,71 @@
1
+ # require 'pp'
2
+
3
+ module Ampere
4
+ # Collections are search results from queries. They can be used like arrays,
5
+ # but you cannot add anything to them.
6
+ class Collection
7
+ attr_reader :raw_array
8
+ attr_reader :model
9
+
10
+ # Instance methods ########################################################
11
+
12
+ def initialize(model_class, array = [])
13
+ @raw_array = array
14
+ @model = model_class
15
+ end
16
+
17
+ # Index into the search results. Lazily loads models when they're accessed.
18
+ def [](idx)
19
+ if @raw_array[idx].is_a?(Ampere::Model) then
20
+ @raw_array[idx]
21
+ else
22
+ # This is still an ID. Find it.
23
+ @raw_array[idx] = @model.find(@raw_array[idx])
24
+ end
25
+ end
26
+
27
+ # Delegates to internal array.
28
+ def count
29
+ @raw_array.count
30
+ end
31
+
32
+ # Delegates to internal array.
33
+ def empty?
34
+ @raw_array.empty?
35
+ end
36
+
37
+ # Returns first item or first n elements.
38
+ def first(n = 0)
39
+ if n == 0 then
40
+ self[0]
41
+ else
42
+ (0..(n - 1)).map{|i| self[i]}
43
+ end
44
+ end
45
+
46
+ # Returns the last item.
47
+ def last
48
+ self[-1]
49
+ end
50
+
51
+ # Delegates to internal array.
52
+ def length
53
+ @raw_array.count
54
+ end
55
+
56
+ # Finds all the un-found items and returns an applicatively-evaluated array.
57
+ def to_a
58
+ @raw_array.map do |m|
59
+ if m.is_a?(Ampere::Model) then
60
+ m
61
+ else
62
+ @model.find(m)
63
+ end
64
+ end
65
+ end
66
+
67
+ # Class methods ###########################################################
68
+
69
+
70
+ end
71
+ end
@@ -0,0 +1,315 @@
1
+ module Ampere
2
+ class Model
3
+ attr_reader :id
4
+
5
+ @fields = []
6
+ @field_defaults = {}
7
+ @indices = []
8
+
9
+ ### Instance methods
10
+
11
+ # Compares this model with another one. If they are literally the same object
12
+ # or have been stored and have the same ID, then they are equal.
13
+ def ==(other)
14
+ super or
15
+ other.instance_of?(self.class) and
16
+ not id.nil? and
17
+ other.id == id
18
+ end
19
+
20
+ # Returns a Hash with all the fields and their values.
21
+ def attributes
22
+ {:id => @id}.tap do |hash|
23
+ self.class.fields.each do |key|
24
+ hash[key] = self.send(key)
25
+ end
26
+ end
27
+ end
28
+
29
+ # Deletes this instance out of the database.
30
+ def destroy
31
+ self.class.delete(@id)
32
+ end
33
+
34
+ # Delegates to ==().
35
+ def eql?(other)
36
+ self == other
37
+ end
38
+
39
+ # Calculates the hash of this object from the attributes hash instead of
40
+ # using Object.hash.
41
+ def hash
42
+ attributes.hash
43
+ end
44
+
45
+ # Initialize an instance like this:
46
+ #
47
+ # Post.new :title => "Kitties: Are They Awesome?"
48
+ def initialize(hash = {})
49
+ hash.each do |k, v|
50
+ if k == 'id' then
51
+ @id = v
52
+ else
53
+ self.send("#{k}=", v)
54
+ end
55
+ end
56
+ end
57
+
58
+ # Returns true if this record has not yet been saved.
59
+ def new?
60
+ @id.nil? or not Ampere.connection.exists(@id)
61
+ end
62
+
63
+ # Reloads this record from the database.
64
+ def reload
65
+ if self.new? then
66
+ raise "Can't reload a new record"
67
+ end
68
+
69
+ self.class.fields.each do |k|
70
+ self.send("#{k}=", Ampere.connection.hget(@id, k))
71
+ end
72
+ self
73
+ end
74
+
75
+ # Saves this record to the database.
76
+ def save
77
+ # Grab a fresh GUID from Redis by incrementing the "__guid" key
78
+ if @id.nil? then
79
+ @id = "#{self.class.to_s.downcase}.#{Ampere.connection.incr('__guid')}"
80
+ end
81
+
82
+ self.attributes.each do |k, v|
83
+ Ampere.connection.hset(@id, k, v)
84
+ end
85
+
86
+ self.class.indices.each do |index|
87
+ if index.class == String or index.class == Symbol then
88
+ Ampere.connection.hset(
89
+ "ampere.index.#{self.class.to_s.downcase}.#{index}",
90
+ instance_variable_get("@#{index}"),
91
+ ([@id] | (Ampere.connection.hget("ampere.index.#{self.class.to_s.downcase}.#{index}", instance_variable_get("@#{index}")) or "")
92
+ .split(/:/)).join(":")
93
+ )
94
+ elsif index.class == Array then
95
+ key = index.map{|i| instance_variable_get("@#{i}")}.join(':')
96
+ val = ([@id] | (Ampere.connection.hget("ampere.index.#{self.class.to_s.downcase}.#{index}", key) or "")
97
+ .split(/:/)).join(":")
98
+ Ampere.connection.hset(
99
+ "ampere.index.#{self.class.to_s.downcase}.#{index.join(':')}",
100
+ key,
101
+ val
102
+ )
103
+ end
104
+ end
105
+ self
106
+ end
107
+
108
+ def update_attribute(key, value)
109
+ raise "Cannot update a nonexistent field!" unless self.class.fields.include?(key)
110
+ self.send("#{key}=", value)
111
+ Ampere.connection.hset(@id, key, value)
112
+ end
113
+
114
+ def update_attributes(hash = {})
115
+ # The efficient way, that I haven't figured out how to do yet:
116
+ # Ampere.connection.hmset(@id, hash)
117
+
118
+ # The inefficient way I know how to do right now:
119
+ hash.each do |k, v|
120
+ update_attribute(k, v)
121
+ end
122
+ end
123
+
124
+ ### Class methods
125
+
126
+ # Returns an array of all the records that have been stored.
127
+ def self.all
128
+ Ampere.connection.keys("#{to_s.downcase}.*").map{|m| find m}
129
+ end
130
+
131
+ # Declares a belongs_to relationship to another model.
132
+ def self.belongs_to(field_name, options = {})
133
+ has_one field_name, options
134
+ end
135
+
136
+ # Like @indices, but only returns the compound indices this class defines.
137
+ def self.compound_indices
138
+ @indices.select{|i| i.class == Array}
139
+ end
140
+
141
+ # Returns the number of instances of this record that have been stored.
142
+ def self.count
143
+ Ampere.connection.keys("#{to_s.downcase}.*").length
144
+ end
145
+
146
+ # Instantiates and saves a new record.
147
+ def self.create(hash = {})
148
+ new(hash).save
149
+ end
150
+
151
+ # Deletes the record with the given ID.
152
+ def self.delete(id)
153
+ Ampere.connection.del(id)
154
+ end
155
+
156
+ # Declares a field. See the README for more details.
157
+ def self.field(name, options = {})
158
+ @fields ||= []
159
+ @field_defaults ||= {}
160
+ @indices ||= []
161
+
162
+ @fields << name
163
+
164
+ attr_accessor :"#{name}"
165
+
166
+ # Handle default value
167
+ @field_defaults[name] = options[:default]
168
+
169
+ define_method :"#{name}" do
170
+ instance_variable_get("@#{name}") or self.class.field_defaults[name]
171
+ end
172
+ end
173
+
174
+ def self.fields
175
+ @fields
176
+ end
177
+
178
+ def self.field_defaults
179
+ @field_defaults
180
+ end
181
+
182
+ # Finds the record with the given ID, or the first that matches the given conditions
183
+ def self.find(options = {})
184
+ if options.class == String then
185
+ if Ampere.connection.exists(options) then
186
+ new(Ampere.connection.hgetall(options))
187
+ else
188
+ nil
189
+ end
190
+ else
191
+ # TODO Write a handler for this case, even if it's an exception
192
+ raise "Cannot find by #{options.class} yet"
193
+ end
194
+ end
195
+
196
+ # Defines a has_one relationship with another model. See the README for more details.
197
+ def self.has_one(field_name, options = {})
198
+ referred_klass_name = (options[:class] or options['class'] or field_name)
199
+ my_klass_name = to_s.downcase
200
+
201
+ field :"#{field_name}_id"
202
+
203
+ define_method(field_name.to_sym) do
204
+ return if self.send("#{field_name}_id").nil?
205
+ eval(referred_klass_name.to_s.capitalize).find(self.send("#{field_name}_id"))
206
+ end
207
+
208
+ define_method(:"#{field_name}=") do |val|
209
+ return nil if val.nil?
210
+ # Set attr with key where referred model is stored
211
+ self.send("#{field_name}_id=", val.id)
212
+ # Also update that model's hash with a pointer back to here
213
+ val.send("#{my_klass_name}_id=", self.send("id"))
214
+ end
215
+ end
216
+
217
+ # Defines a has_many relationship with another model. See the README for more details.
218
+ def self.has_many(field_name, options = {})
219
+ klass_name = (options[:class] or options['class'] or field_name.to_s.gsub(/s$/, ''))
220
+ my_klass_name = to_s.downcase
221
+
222
+ define_method(:"#{field_name}") do
223
+ (Ampere.connection.smembers("#{to_s.downcase}.#{self.id}.has_many.#{field_name}")).map do |id|
224
+ eval(klass_name.to_s.capitalize).find(id)
225
+ end
226
+ end
227
+
228
+ define_method(:"#{field_name}=") do |val|
229
+ val.each do |v|
230
+ Ampere.connection.sadd("#{to_s.downcase}.#{self.id}.has_many.#{field_name}", v.id)
231
+ # Set pointer for belongs_to
232
+ Ampere.connection.hset(v.id, "#{my_klass_name}_id", self.send("id"))
233
+ end
234
+ end
235
+ end
236
+
237
+ # Defines an index. See the README for more details.
238
+ def self.index(field_name, options = {})
239
+ @fields ||= []
240
+ @field_defaults ||= {}
241
+ @indices ||= []
242
+ if field_name.class == String or field_name.class == Symbol then
243
+ raise "Can't index a nonexistent field!" unless @fields.include?(field_name)
244
+ elsif field_name.class == Array then
245
+ field_name.each{|f| raise "Can't index a nonexistent field!" unless @fields.include?(f)}
246
+ field_name.sort!
247
+ else
248
+ raise "Can't index a #{field_name.class}"
249
+ end
250
+
251
+ @indices << field_name
252
+ end
253
+
254
+ def self.indices
255
+ @indices
256
+ end
257
+
258
+ # Finds an array of records which match the given conditions. This method is
259
+ # much faster when all the fields given are indexed.
260
+ def self.where(options = {})
261
+ if options.empty? then
262
+ Ampere::Collection.new(eval(to_s), [])
263
+ else
264
+ indexed_fields = (options.keys & @indices) + compound_indices_for(options)
265
+ nonindexed_fields = (options.keys - @indices) - compound_indices_for(options).flatten
266
+
267
+ results = nil
268
+
269
+ unless indexed_fields.empty?
270
+ indexed_fields.map {|key|
271
+ if key.class == String or key.class == Symbol then
272
+ Ampere.connection.hget("ampere.index.#{to_s.downcase}.#{key}", options[key]).split(/:/) #.map {|id| find(id)}
273
+ else
274
+ # Compound index
275
+ Ampere.connection.hget(
276
+ "ampere.index.#{to_s.downcase}.#{key.join(':')}",
277
+ key.map{|k| options[k]}.join(':')
278
+ ).split(/:/) #.map {|id| find(id)}
279
+ end
280
+ }.each {|s|
281
+ return s if s.empty?
282
+
283
+ if results.nil? then
284
+ results = s
285
+ else
286
+ results &= s
287
+ end
288
+ }
289
+ end
290
+
291
+ unless nonindexed_fields.empty?
292
+ results = all if results.nil?
293
+ results.map!{|r| r.class == String ? find(r) : r}
294
+ nonindexed_fields.each do |key|
295
+ results.select!{|r| r.send(key) == options[key]}
296
+ end
297
+ end
298
+
299
+ # TODO The eval(to_s) trick seems a little... ghetto.
300
+ Ampere::Collection.new(eval(to_s), results.reverse)
301
+ end
302
+ end
303
+
304
+ private
305
+
306
+ def self.compound_indices_for(query)
307
+ compound_indices.select{|ci|
308
+ (query.keys - ci).empty?
309
+ }
310
+ end
311
+
312
+
313
+ end
314
+
315
+ end