activerecord-reputation-system 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
data/LICENSE ADDED
@@ -0,0 +1,177 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
data/README.md ADDED
@@ -0,0 +1,255 @@
1
+ ## Active Record Reputation System [![Build Status](https://secure.travis-ci.org/twitter/activerecord-reputation-system.png)](http://travis-ci.org/twitter/activerecord-reputation-system)
2
+
3
+ The Active Record Reputation System helps you discover more about your application and make better decisions. The Reputation System gem makes it easy to integrate reputation systems into Rails applications, decouple the system from the main application and provide guidelines for good design of reputation systems.
4
+
5
+ ## Concept
6
+
7
+ In this gem, the reputation system is described as a network of reputations where updates are triggered by evaluations and reputation values are computed and propagated by the network. In this network, reputations with values directly computed from evaluations are called primary reputations and reputations with values indirectly computed from evaluations are called non-primary reputations. The following is an abstract view of a possible Reputation System:
8
+
9
+ ![Alt text](./activerecord-reputation-system/raw/master/abs_rs.png "Abstract view of Reputation System")
10
+
11
+ ## Installation
12
+
13
+ `gem install reputation_system && rails generator reputation_system && rake db:migrate`
14
+
15
+ ## Usage Example
16
+
17
+ Let's say we want to keep track of user karma in Q&A site where user karma is sum of questioning skill and answering skill. Questioning skill is sum of votes for user's questions and Answering skill is sum of average rating of user's answers. This can be defined as follow:
18
+ ```ruby
19
+ class User < ActiveRecord::Base
20
+ has_many :answers
21
+ has_many :questions
22
+
23
+ has_reputation :karma,
24
+ :source => [
25
+ { :reputation => :questioning_skill, :weight => 0.8 },
26
+ { :reputation => :answering_skill }],
27
+ aggregated_by => :sum
28
+
29
+ has_reputation :questioning_skill,
30
+ :source => { :reputation => :votes, :of => :questions },
31
+ :aggregated_by => :sum
32
+
33
+ has_reputation :answering_skill,
34
+ :source => { :reputation => :avg_rating, :of => :answers },
35
+ :aggregated_by => :sum
36
+ end
37
+
38
+ class Answer < ActiveRecord::Base
39
+ belongs_to :user, :as => :author
40
+
41
+ has_reputation :avg_rating,
42
+ :source => :user,
43
+ :aggregated_by => :average,
44
+ :source_of => [{ :reputation => :answering_skill, :of => :author }]
45
+ end
46
+
47
+
48
+ class Question < ActiveRecord::Base
49
+ belongs_to :user
50
+
51
+ has_reputation :votes,
52
+ :source => :user,
53
+ :aggregated_by => :sum
54
+ end
55
+ ```
56
+
57
+ Once reputation system is defined, evaluations for answers and questions can be added as follow:
58
+ ```ruby
59
+ @answer.add_evaluation(:avg_rating, 3, @user)
60
+ @question.add_evaluation(:votes, 1, @user)
61
+ ```
62
+
63
+ Reputation value can be accessed as follow:
64
+ ```ruby
65
+ @answer.reputation_value_for(:avg_rating)
66
+ @question.reputation_value_for(:votes)
67
+ @user.reputation_value_for(:karma)
68
+ ```
69
+
70
+ ## Defining Reputation System
71
+
72
+ All reputations can be defined in their target ActiveRecord models like this:
73
+ ```ruby
74
+ # Primary Reputation
75
+ has_reputation :name,
76
+ :source => source,
77
+ :aggregated_by => process,
78
+ :source_of => [{:reputation => name, :of => attribute}, ...],
79
+ :init_value => initial_value
80
+
81
+ # Non Primary Reputation
82
+ has_reputation :name,
83
+ :source => [{:reputation => name, :of => attribute, :weight => weight}, ...],
84
+ :aggregated_by => process,
85
+ :source_of => [{:reputation => name, :of => attribute}, ...],
86
+ :init_value => initial_value
87
+ ```
88
+ * :name is the name of the reputation.
89
+ * :source is a source of the reputation. If it is primary reputation, it takes a class name as input. If it's a non-primary reputation, it takes one or more source definitions, which consist of:
90
+ ** :reputation - name of reputation to be used as a source.
91
+ ** :of - attribute name (It also accepts a proc as an argument) of the ActiveRecord model which has the source reputation. (default: :self)
92
+ ** :weight (optional) - weight value to be used for aggregation (default: 1).
93
+ * :aggregated_by is a mathematical process to be used to aggregate reputation or evaluation values. The following processes are available (each value is weighted by a predefined weight):
94
+ ** average - averages all values received.
95
+ ** sum - sums up all the values received.
96
+ ** product - multiplies all the values received.
97
+ * :source_of (optional) - just like active record association, you don't need to define this if a name can be derived from class name; otherwise if the reputation is used as a part of a source belonging to other reputations, you must define. It takes one or more source definitions, which consists of:
98
+ ** :reputation - name of the reputation to be used as a source.
99
+ ** :of - attribute name (It also accepts a proc as an argument) of the ActiveRecord model which has the source reputation. (default: :self)
100
+ * :init_value (optional) - initial reputation value assigned to new reputation. It is 0 for average and sum process and 1 for product by default.
101
+
102
+ ## Evaluation
103
+ ```ruby
104
+ # Adds an evaluation to the reputation with the specified name.
105
+ add_evaluation(reputation_name, evaluation_value, source)
106
+
107
+ # Updates an existing evaluation of the reputation with the specified name by the specified source.
108
+ update_evaluation(reputation_name, evaluation_value, source)
109
+
110
+ # Adds an evaluation to the reputation with the specified name if it exists; otherwise it updates the existing reputation.
111
+ add_or_update_evaluation(reputation_name, evaluation_value, source)
112
+
113
+ # Deletes an evaluation from the reputation with the specified name submitted by the specified source. It returns nil if it does not exist.
114
+ delete_evaluation(reputation_name, source)
115
+
116
+ # Deletes an evaluation from the reputation with the specified name submitted by specified source. Raises an exception if it does not exist.
117
+ delete_evaluation!(reputation_name, source)
118
+ ```
119
+
120
+ ## Reputation
121
+ ```ruby
122
+ # Returns the reputation value of the reputation with the given name.
123
+ reputation_value_for(reputation_name)
124
+
125
+ # Returns the reputation rank of the reputation with the given name.
126
+ rank_for(reputation_name)
127
+
128
+ # Returns the normalized reputation value of the reputation with the given name. The normalization is computed using the following equation (assuming linear distribution):
129
+ # normalized_value = (x - min) / (max - min) if max - min&nbsp;is not 0
130
+ # normalized_value = 1 if max - min is 0
131
+ normalized_reputation_value_for(reputation_name)
132
+
133
+ # Activates all reputations in the record. Active reputations are used when computing ranks or normalized reputation values.
134
+ activate_all_reputations
135
+
136
+ # Deactivates all reputations in the record. Inactive reputations are not used when computing ranks or normalized reputation values.
137
+ deactivate_all_reputations
138
+
139
+ # Checks if reputation is active.
140
+ reputations_activated?(reputation_name)
141
+ ```
142
+
143
+ ## Querying with Reputation
144
+ ```ruby
145
+ # Includes the specified reputation value for the given name via a normal Active Record find query.
146
+ ActiveRecord::Base.find_with_reputation(reputation_name, find_scope, options)
147
+ # For example:
148
+ ActiveRecord::Base.find_with_reputation(:maturity, :all, {:select => "id", :conditions => ["maturity > ?", 3], :order => "maturity"})
149
+
150
+ # Includes the specified normalized reputation value for the given name via a normal Active Record find query.
151
+ ActiveRecord::Base.find_with_normalized_reputation(reputation_name, find_options)
152
+ # For example:
153
+ ActiveRecord::Base.find_with_normalized_reputation(:maturity, :all, {:select => "id", :conditions => ["maturity > ?", 3], :order => "maturity"})
154
+
155
+ # Includes the specified reputation value for the given name via a normal Active Record count query.
156
+ ActiveRecord::Base.count_with_reputation(reputation_name, find_options)
157
+
158
+ # This method returns a SQL statement rather than a query result.
159
+ ActiveRecord::Base.find_with_reputation_sql(reputation_name, find_options)
160
+ ```
161
+
162
+ ## Advanced Topics
163
+ ### Scope
164
+ Reputations can have different scopes to provide additional context.
165
+
166
+ For example, let's say `question` has a reputation called `difficulty`. You might want to keep track of that reputation by country, such that each question has a different difficulty rating in each country.
167
+
168
+ Scopes can be defined like this:
169
+ ```ruby
170
+ has_reputation :name,
171
+ ...
172
+ :scopes => [:scope1, :scope2, ...]
173
+ ```
174
+ Once scopes are defined, evaluations can be added in the context of defined scopes:
175
+ ```ruby
176
+ add_evaluation(:reputation_name, :scope)
177
+ ```
178
+ Also, reputations can be accessed in the context of scopes:
179
+ ```ruby
180
+ reputation_value_for(:reputation_name, :scope)
181
+ ```
182
+ To use a scoped reputation as a source in another reputation, try this:
183
+ ```ruby
184
+ has_reputation :rep1,
185
+ :source => {:reputation => :rep2, :scope => :scope1}
186
+ ...
187
+ has_reputation :rep2,
188
+ ...
189
+ :scopes => [:scope1, :scope2, ...],
190
+ :source_of => {:reputation => :rep1, :defined_for_scope => [:scope1]}
191
+ ```
192
+ To execute an Active Record query using a scoped reputation, try this:
193
+ ```ruby
194
+ ActiveRecord::Base.find_with_reputation(:reputation_name, :scope, :find_options)
195
+ ```
196
+ There are a few more helper methods available for scopes:
197
+ ```ruby
198
+ # Allows you to add a scope dynamically.
199
+ add_scope_for(reputation_name, scope)
200
+
201
+ # Returns true if the reputation has scopes.
202
+ has_scopes?(reputation_name)
203
+
204
+ # Returns true if the reputation has a given scope.
205
+ has_scope?(reputation_name, scope)
206
+ ```
207
+
208
+ ### Performance
209
+
210
+ For applications with large data set, computation of reputation values can be expensive. Therefore, it is common to perform the computation asynchronously (in batch). If you wish to asynchronously compute reputation values, I strongly recommend you to use [collectiveidea's Delayed Job](https://github.com/collectiveidea/delayed_job). For example:
211
+
212
+ ```ruby
213
+ class User < ActiveRecord
214
+ has_reputation :karma,
215
+ :source => :user,
216
+ :aggregated_by => :sum
217
+
218
+ handle_asynchronously :add_evaluation
219
+ handle_asynchronously :update_evaluation
220
+ handle_asynchronously :delete_evaluation
221
+ end
222
+ ```
223
+
224
+ ### Reflect Past Data
225
+
226
+ If you wish to reflect past data into new reputation system, I recommend you write a script which simulates all evaluations that would have happened in the past. You probably want to use [collectiveidea's Delayed Job](https://github.com/collectiveidea/delayed_job) to enqueue those past evaluation tasks first and then new ongoing evaluation task so that evaluations are performed in proper time sequence.
227
+
228
+ ## Running Tests
229
+
230
+ `rake` should do the trick. Tests are written in RSpec.
231
+
232
+ ## Versioning
233
+
234
+ For transparency and insight into our release cycle, releases will be numbered with the follow format:
235
+
236
+ `<major>.<minor>.<patch>`
237
+
238
+ And constructed with the following guidelines:
239
+
240
+ * Breaking backwards compatibility bumps the major
241
+ * New additions without breaking backwards compatibility bumps the minor
242
+ * Bug fixes and misc changes bump the patch
243
+
244
+ For more information on semantic versioning, please visit http://semver.org/.
245
+
246
+ ## Authors
247
+
248
+ * Katsuya Noguchi: http://github.com/katsuyan
249
+ * Inspired by ["Building Web Reputation Systems" by Randy Farmer and Bryce Glass](http://shop.oreilly.com/product/9780596159801.do)
250
+
251
+ ## License
252
+
253
+ Copyright 2012 Twitter, Inc.
254
+
255
+ Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
data/Rakefile ADDED
@@ -0,0 +1,20 @@
1
+ require 'rdoc/task'
2
+ require 'rubygems'
3
+ require 'rubygems/package_task'
4
+ require 'rspec/core/rake_task'
5
+
6
+ desc 'Default: run specs.'
7
+ task :default => :rspec
8
+
9
+ desc 'Run the specs'
10
+ RSpec::Core::RakeTask.new(:rspec) do |t|
11
+ t.rspec_opts = ['--color']
12
+ t.pattern = './spec/**/*_spec.rb'
13
+ end
14
+
15
+ spec = Gem::Specification.load("#{File.dirname(__FILE__)}/activerecord-reputation-system.gemspec")
16
+
17
+ desc "Package gem."
18
+ Gem::PackageTask.new(spec) do |pkg|
19
+ pkg.gem_spec = spec
20
+ end