di-acts-as-taggable 1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/CHANGELOG ADDED
@@ -0,0 +1,18 @@
1
+ == 2008-07-17
2
+
3
+ * Can now use a named_scope to find tags!
4
+
5
+ == 2008-06-23
6
+
7
+ * Can now find related objects of another class (tristanzdunn)
8
+ * Removed extraneous down migration cruft (azabaj)
9
+
10
+ == 2008-06-09
11
+
12
+ * Added support for Single Table Inheritance
13
+ * Adding gemspec and rails/init.rb for gemified plugin
14
+
15
+ == 2007-12-12
16
+
17
+ * Added ability to use dynamic tag contexts
18
+ * Fixed missing migration generator
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2007 Michael Bleigh and Intridea Inc.
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README ADDED
@@ -0,0 +1,194 @@
1
+ ActsAsTaggableOn
2
+ ================
3
+
4
+ This plugin was originally based on Acts as Taggable on Steroids by Jonathan Viney.
5
+ It has evolved substantially since that point, but all credit goes to him for the
6
+ initial tagging functionality that so many people have used.
7
+
8
+ For instance, in a social network, a user might have tags that are called skills,
9
+ interests, sports, and more. There is no real way to differentiate between tags and
10
+ so an implementation of this type is not possible with acts as taggable on steroids.
11
+
12
+ Enter Acts as Taggable On. Rather than tying functionality to a specific keyword
13
+ (namely "tags"), acts as taggable on allows you to specify an arbitrary number of
14
+ tag "contexts" that can be used locally or in combination in the same way steroids
15
+ was used.
16
+
17
+ Installation
18
+ ============
19
+
20
+ Plugin
21
+ ------
22
+
23
+ Acts As Taggable On is available both as a gem and as a traditional plugin. For the
24
+ traditional plugin you can install like so (Rails 2.1 or later):
25
+
26
+ script/plugin install git://github.com/mbleigh/acts-as-taggable-on.git
27
+
28
+ For earlier versions:
29
+
30
+ git clone git://github.com/mbleigh/acts-as-taggable-on.git vendor/plugins/acts-as-taggable-on
31
+
32
+ GemPlugin
33
+ ---------
34
+
35
+ Acts As Taggable On is also available as a gem plugin using Rails 2.1's gem dependencies.
36
+ To install the gem, add this to your config/environment.rb:
37
+
38
+ config.gem "acts-as-taggable-on", :source => "http://gemcutter.org"
39
+
40
+ After that, you can run "rake gems:install" to install the gem if you don't already have it.
41
+
42
+ ** NOTE **
43
+ Some issues have been experienced with "rake gems:install". If that doesn't work to install the gem,
44
+ try just installing it as a normal gem:
45
+
46
+ gem install acts-as-taggable-on --source http://gemcutter.org
47
+
48
+ Post Installation (Rails)
49
+ -------------------------
50
+ 1. script/generate acts_as_taggable_on_migration
51
+ 2. rake db:migrate
52
+
53
+ Testing
54
+ =======
55
+
56
+ Acts As Taggable On uses RSpec for its test coverage. Inside the plugin
57
+ directory, you can run the specs with:
58
+
59
+ rake spec
60
+
61
+
62
+ If you already have RSpec on your application, the specs will run while using:
63
+
64
+ rake spec:plugins
65
+
66
+
67
+ Example
68
+ =======
69
+
70
+ class User < ActiveRecord::Base
71
+ acts_as_taggable_on :tags, :skills, :interests
72
+ end
73
+
74
+ @user = User.new(:name => "Bobby")
75
+ @user.tag_list = "awesome, slick, hefty" # this should be familiar
76
+ @user.skill_list = "joking, clowning, boxing" # but you can do it for any context!
77
+ @user.skill_list # => ["joking","clowning","boxing"] as TagList
78
+ @user.save
79
+
80
+ @user.tags # => [<Tag name:"awesome">,<Tag name:"slick">,<Tag name:"hefty">]
81
+ @user.skills # => [<Tag name:"joking">,<Tag name:"clowning">,<Tag name:"boxing">]
82
+
83
+ # The old way
84
+ User.find_tagged_with("awesome", :on => :tags) # => [@user]
85
+ User.find_tagged_with("awesome", :on => :skills) # => []
86
+
87
+ # The better way (utilizes named_scope)
88
+ User.tagged_with("awesome", :on => :tags) # => [@user]
89
+ User.tagged_with("awesome", :on => :skills) # => []
90
+
91
+ @frankie = User.create(:name => "Frankie", :skill_list => "joking, flying, eating")
92
+ User.skill_counts # => [<Tag name="joking" count=2>,<Tag name="clowning" count=1>...]
93
+ @frankie.skill_counts
94
+
95
+ Finding Tagged Objects
96
+ ======================
97
+
98
+ Acts As Taggable On utilizes Rails 2.1's named_scope to create an association
99
+ for tags. This way you can mix and match to filter down your results, and it
100
+ also improves compatibility with the will_paginate gem:
101
+
102
+ class User < ActiveRecord::Base
103
+ acts_as_taggable_on :tags
104
+ named_scope :by_join_date, :order => "created_at DESC"
105
+ end
106
+
107
+ User.tagged_with("awesome").by_date
108
+ User.tagged_with("awesome").by_date.paginate(:page => params[:page], :per_page => 20)
109
+
110
+ Relationships
111
+ =============
112
+
113
+ You can find objects of the same type based on similar tags on certain contexts.
114
+ Also, objects will be returned in descending order based on the total number of
115
+ matched tags.
116
+
117
+ @bobby = User.find_by_name("Bobby")
118
+ @bobby.skill_list # => ["jogging", "diving"]
119
+
120
+ @frankie = User.find_by_name("Frankie")
121
+ @frankie.skill_list # => ["hacking"]
122
+
123
+ @tom = User.find_by_name("Tom")
124
+ @tom.skill_list # => ["hacking", "jogging", "diving"]
125
+
126
+ @tom.find_related_skills # => [<User name="Bobby">,<User name="Frankie">]
127
+ @bobby.find_related_skills # => [<User name="Tom">]
128
+ @frankie.find_related_skills # => [<User name="Tom">]
129
+
130
+
131
+ Dynamic Tag Contexts
132
+ ====================
133
+
134
+ In addition to the generated tag contexts in the definition, it is also possible
135
+ to allow for dynamic tag contexts (this could be user generated tag contexts!)
136
+
137
+ @user = User.new(:name => "Bobby")
138
+ @user.set_tag_list_on(:customs, "same, as, tag, list")
139
+ @user.tag_list_on(:customs) # => ["same","as","tag","list"]
140
+ @user.save
141
+ @user.tags_on(:customs) # => [<Tag name='same'>,...]
142
+ @user.tag_counts_on(:customs)
143
+ User.find_tagged_with("same", :on => :customs) # => [@user]
144
+
145
+ Tag Ownership
146
+ =============
147
+
148
+ Tags can have owners:
149
+
150
+ class User < ActiveRecord::Base
151
+ acts_as_tagger
152
+ end
153
+
154
+ class Photo < ActiveRecord::Base
155
+ acts_as_taggable_on :locations
156
+ end
157
+
158
+ @some_user.tag(@some_photo, :with => "paris, normandy", :on => :locations)
159
+ @some_user.owned_taggings
160
+ @some_user.owned_tags
161
+ @some_photo.locations_from(@some_user)
162
+
163
+ Caveats, Uncharted Waters
164
+ =========================
165
+
166
+ This plugin is still under active development. Tag caching has not
167
+ been thoroughly (or even casually) tested and may not work as expected.
168
+
169
+ Contributors
170
+ ============
171
+
172
+ * Michael Bleigh - Original Author
173
+ * Brendan Lim - Related Objects
174
+ * Pradeep Elankumaran - Taggers
175
+ * Sinclair Bain - Patch King
176
+
177
+ Patch Contributors
178
+ ------------------
179
+
180
+ * tristanzdunn - Related objects of other classes
181
+ * azabaj - Fixed migrate down
182
+ * Peter Cooper - named_scope fix
183
+ * slainer68 - STI fix
184
+ * harrylove - migration instructions and fix-ups
185
+ * lawrencepit - cached tag work
186
+
187
+ Resources
188
+ =========
189
+
190
+ * Acts As Community - http://www.actsascommunity.com/projects/acts-as-taggable-on
191
+ * GitHub - http://github.com/mbleigh/acts-as-taggable-on
192
+ * Lighthouse - http://mbleigh.lighthouseapp.com/projects/10116-acts-as-taggable-on
193
+
194
+ Copyright (c) 2007 Michael Bleigh (http://mbleigh.com/) and Intridea Inc. (http://intridea.com/), released under the MIT license
data/Rakefile ADDED
@@ -0,0 +1,23 @@
1
+ require 'spec/rake/spectask'
2
+
3
+ begin
4
+ require 'jeweler'
5
+ Jeweler::Tasks.new do |gemspec|
6
+ gemspec.name = "acts-as-taggable-on"
7
+ gemspec.summary = "ActsAsTaggableOn is a tagging plugin for Rails that provides multiple tagging contexts on a single model."
8
+ gemspec.description = "With ActsAsTaggableOn, you could tag a single model on several contexts, such as skills, interests, and awards. It also provides other advanced functionality."
9
+ gemspec.email = "michael@intridea.com"
10
+ gemspec.homepage = "http://github.com/mbleigh/acts-as-taggable-on"
11
+ gemspec.authors = ["Michael Bleigh"]
12
+ gemspec.files = FileList["[A-Z]*", "{lib,spec,rails}/**/*"] - FileList["**/*.log"]
13
+ end
14
+ Jeweler::GemcutterTasks.new
15
+ rescue LoadError
16
+ puts "Jeweler not available. Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com"
17
+ end
18
+
19
+ desc 'Default: run specs'
20
+ task :default => :spec
21
+ Spec::Rake::SpecTask.new do |t|
22
+ t.spec_files = FileList["spec/**/*_spec.rb"]
23
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 1.0.10
@@ -0,0 +1,6 @@
1
+ require 'acts_as_taggable_on/acts_as_taggable_on'
2
+ require 'acts_as_taggable_on/acts_as_tagger'
3
+ require 'acts_as_taggable_on/tag'
4
+ require 'acts_as_taggable_on/tag_list'
5
+ require 'acts_as_taggable_on/tags_helper'
6
+ require 'acts_as_taggable_on/tagging'
@@ -0,0 +1,362 @@
1
+ module ActiveRecord
2
+ module Acts
3
+ module TaggableOn
4
+ def self.included(base)
5
+ base.extend(ClassMethods)
6
+ end
7
+
8
+ module ClassMethods
9
+ def taggable?
10
+ false
11
+ end
12
+
13
+ def acts_as_taggable
14
+ acts_as_taggable_on :tags
15
+ end
16
+
17
+ def acts_as_taggable_on(*args)
18
+ args.flatten! if args
19
+ args.compact! if args
20
+ for tag_type in args
21
+ tag_type = tag_type.to_s
22
+ # use aliased_join_table_name for context condition so that sphix can join multiple
23
+ # tag references from same model without getting an ambiguous column error
24
+ self.class_eval do
25
+ has_many "#{tag_type.singularize}_taggings".to_sym, :as => :taggable, :dependent => :destroy,
26
+ :include => :tag, :conditions => ['#{aliased_join_table_name rescue "taggings"}.context = ?',tag_type], :class_name => "Tagging"
27
+ has_many "#{tag_type}".to_sym, :through => "#{tag_type.singularize}_taggings".to_sym, :source => :tag
28
+ end
29
+
30
+ self.class_eval <<-RUBY
31
+ def self.taggable?
32
+ true
33
+ end
34
+
35
+ def self.caching_#{tag_type.singularize}_list?
36
+ caching_tag_list_on?("#{tag_type}")
37
+ end
38
+
39
+ def self.#{tag_type.singularize}_counts(options={})
40
+ tag_counts_on('#{tag_type}',options)
41
+ end
42
+
43
+ def #{tag_type.singularize}_list
44
+ tag_list_on('#{tag_type}')
45
+ end
46
+
47
+ def #{tag_type.singularize}_list=(new_tags)
48
+ set_tag_list_on('#{tag_type}',new_tags)
49
+ end
50
+
51
+ def #{tag_type.singularize}_counts(options = {})
52
+ tag_counts_on('#{tag_type}',options)
53
+ end
54
+
55
+ def #{tag_type}_from(owner)
56
+ tag_list_on('#{tag_type}', owner)
57
+ end
58
+
59
+ def find_related_#{tag_type}(options = {})
60
+ related_tags_for('#{tag_type}', self.class, options)
61
+ end
62
+ alias_method :find_related_on_#{tag_type}, :find_related_#{tag_type}
63
+
64
+ def find_related_#{tag_type}_for(klass, options = {})
65
+ related_tags_for('#{tag_type}', klass, options)
66
+ end
67
+
68
+ def top_#{tag_type}(limit = 10)
69
+ tag_counts_on('#{tag_type}', :order => 'count desc', :limit => limit.to_i)
70
+ end
71
+
72
+ def self.top_#{tag_type}(limit = 10)
73
+ tag_counts_on('#{tag_type}', :order => 'count desc', :limit => limit.to_i)
74
+ end
75
+ RUBY
76
+ end
77
+
78
+ if respond_to?(:tag_types)
79
+ write_inheritable_attribute( :tag_types, (tag_types + args).uniq )
80
+ else
81
+ self.class_eval do
82
+ write_inheritable_attribute(:tag_types, args.uniq)
83
+ class_inheritable_reader :tag_types
84
+
85
+ has_many :taggings, :as => :taggable, :dependent => :destroy, :include => :tag
86
+ has_many :base_tags, :class_name => "Tag", :through => :taggings, :source => :tag
87
+
88
+ attr_writer :custom_contexts
89
+
90
+ before_save :save_cached_tag_list
91
+ after_save :save_tags
92
+
93
+ if respond_to?(:named_scope)
94
+ named_scope :tagged_with, lambda{ |*args|
95
+ find_options_for_find_tagged_with(*args)
96
+ }
97
+ end
98
+ end
99
+
100
+ include ActiveRecord::Acts::TaggableOn::InstanceMethods
101
+ extend ActiveRecord::Acts::TaggableOn::SingletonMethods
102
+ alias_method_chain :reload, :tag_list
103
+ end
104
+ end
105
+
106
+ def is_taggable?
107
+ false
108
+ end
109
+ end
110
+
111
+ module SingletonMethods
112
+ # Pass either a tag string, or an array of strings or tags
113
+ #
114
+ # Options:
115
+ # :exclude - Find models that are not tagged with the given tags
116
+ # :match_all - Find models that match all of the given tags, not just one
117
+ # :conditions - A piece of SQL conditions to add to the query
118
+ # :on - scopes the find to a context
119
+ def find_tagged_with(*args)
120
+ options = find_options_for_find_tagged_with(*args)
121
+ options.blank? ? [] : find(:all,options)
122
+ end
123
+
124
+ def caching_tag_list_on?(context)
125
+ column_names.include?("cached_#{context.to_s.singularize}_list")
126
+ end
127
+
128
+ def tag_counts_on(context, options = {})
129
+ Tag.find(:all, find_options_for_tag_counts(options.merge({:on => context.to_s})))
130
+ end
131
+
132
+ def all_tag_counts(options = {})
133
+ Tag.find(:all, find_options_for_tag_counts(options))
134
+ end
135
+
136
+ def find_options_for_find_tagged_with(tags, options = {})
137
+ tags = TagList.from(tags)
138
+
139
+ return {} if tags.empty?
140
+
141
+ joins = []
142
+ conditions = []
143
+
144
+ context = options.delete(:on)
145
+
146
+
147
+ if options.delete(:exclude)
148
+ tags_conditions = tags.map { |t| sanitize_sql(["#{Tag.table_name}.name LIKE ?", t]) }.join(" OR ")
149
+ conditions << "#{table_name}.#{primary_key} NOT IN (SELECT #{Tagging.table_name}.taggable_id FROM #{Tagging.table_name} JOIN #{Tag.table_name} ON #{Tagging.table_name}.tag_id = #{Tag.table_name}.id AND (#{tags_conditions}) WHERE #{Tagging.table_name}.taggable_type = #{quote_value(base_class.name)})"
150
+
151
+ else
152
+ tags.each do |tag|
153
+ safe_tag = tag.gsub(/[^a-zA-Z0-9]/, '')
154
+ prefix = "#{safe_tag}_#{rand(1024)}"
155
+
156
+ taggings_alias = "#{table_name}_taggings_#{prefix}"
157
+ tags_alias = "#{table_name}_tags_#{prefix}"
158
+
159
+ tagging_join = "JOIN #{Tagging.table_name} #{taggings_alias}" +
160
+ " ON #{taggings_alias}.taggable_id = #{table_name}.#{primary_key}" +
161
+ " AND #{taggings_alias}.taggable_type = #{quote_value(base_class.name)}"
162
+ tagging_join << " AND " + sanitize_sql(["#{taggings_alias}.context = ?", context.to_s]) if context
163
+
164
+ tag_join = "JOIN #{Tag.table_name} #{tags_alias}" +
165
+ " ON #{tags_alias}.id = #{taggings_alias}.tag_id" +
166
+ " AND " + sanitize_sql(["#{tags_alias}.name = ?", tag])
167
+
168
+ joins << tagging_join
169
+ joins << tag_join
170
+ end
171
+ end
172
+
173
+ taggings_alias, tags_alias = "#{table_name}_taggings_group", "#{table_name}_tags_group"
174
+
175
+ if options.delete(:match_all)
176
+ joins << "LEFT OUTER JOIN #{Tagging.table_name} #{taggings_alias}" +
177
+ " ON #{taggings_alias}.taggable_id = #{table_name}.#{primary_key}" +
178
+ " AND #{taggings_alias}.taggable_type = #{quote_value(base_class.name)}"
179
+
180
+ group = "#{table_name}.#{primary_key} HAVING COUNT(#{taggings_alias}.taggable_id) = #{tags.size}"
181
+ end
182
+
183
+ { :joins => joins.join(" "),
184
+ :group => group,
185
+ :conditions => conditions.join(" AND ") }.update(options)
186
+ end
187
+
188
+ # Calculate the tag counts for all tags.
189
+ #
190
+ # Options:
191
+ # :start_at - Restrict the tags to those created after a certain time
192
+ # :end_at - Restrict the tags to those created before a certain time
193
+ # :conditions - A piece of SQL conditions to add to the query
194
+ # :limit - The maximum number of tags to return
195
+ # :order - A piece of SQL to order by. Eg 'tags.count desc' or 'taggings.created_at desc'
196
+ # :at_least - Exclude tags with a frequency less than the given value
197
+ # :at_most - Exclude tags with a frequency greater than the given value
198
+ # :on - Scope the find to only include a certain context
199
+ def find_options_for_tag_counts(options = {})
200
+ options.assert_valid_keys :start_at, :end_at, :conditions, :at_least, :at_most, :order, :limit, :on, :id
201
+
202
+ scope = scope(:find)
203
+ start_at = sanitize_sql(["#{Tagging.table_name}.created_at >= ?", options.delete(:start_at)]) if options[:start_at]
204
+ end_at = sanitize_sql(["#{Tagging.table_name}.created_at <= ?", options.delete(:end_at)]) if options[:end_at]
205
+
206
+ taggable_type = sanitize_sql(["#{Tagging.table_name}.taggable_type = ?", base_class.name])
207
+ taggable_id = sanitize_sql(["#{Tagging.table_name}.taggable_id = ?", options.delete(:id)]) if options[:id]
208
+ options[:conditions] = sanitize_sql(options[:conditions]) if options[:conditions]
209
+
210
+ conditions = [
211
+ taggable_type,
212
+ taggable_id,
213
+ options[:conditions],
214
+ start_at,
215
+ end_at
216
+ ]
217
+
218
+ conditions = conditions.compact.join(' AND ')
219
+ conditions = merge_conditions(conditions, scope[:conditions]) if scope
220
+
221
+ joins = ["LEFT OUTER JOIN #{Tagging.table_name} ON #{Tag.table_name}.id = #{Tagging.table_name}.tag_id"]
222
+ joins << sanitize_sql(["AND #{Tagging.table_name}.context = ?",options.delete(:on).to_s]) unless options[:on].nil?
223
+
224
+ joins << " INNER JOIN #{table_name} ON #{table_name}.#{primary_key} = #{Tagging.table_name}.taggable_id"
225
+ unless self.descends_from_active_record?
226
+ # Current model is STI descendant, so add type checking to the join condition
227
+ joins << " AND #{table_name}.#{self.inheritance_column} = '#{self.name}'"
228
+ end
229
+
230
+ joins << scope[:joins] if scope && scope[:joins]
231
+
232
+ at_least = sanitize_sql(['COUNT(*) >= ?', options.delete(:at_least)]) if options[:at_least]
233
+ at_most = sanitize_sql(['COUNT(*) <= ?', options.delete(:at_most)]) if options[:at_most]
234
+ having = [at_least, at_most].compact.join(' AND ')
235
+ group_by = "#{Tag.table_name}.id HAVING COUNT(*) > 0"
236
+ group_by << " AND #{having}" unless having.blank?
237
+
238
+ { :select => "#{Tag.table_name}.*, COUNT(*) AS count",
239
+ :joins => joins.join(" "),
240
+ :conditions => conditions,
241
+ :group => group_by,
242
+ :limit => options[:limit],
243
+ :order => options[:order]
244
+ }
245
+ end
246
+
247
+ def is_taggable?
248
+ true
249
+ end
250
+ end
251
+
252
+ module InstanceMethods
253
+
254
+ def tag_types
255
+ self.class.tag_types
256
+ end
257
+
258
+ def custom_contexts
259
+ @custom_contexts ||= []
260
+ end
261
+
262
+ def is_taggable?
263
+ self.class.is_taggable?
264
+ end
265
+
266
+ def add_custom_context(value)
267
+ custom_contexts << value.to_s unless custom_contexts.include?(value.to_s) or self.class.tag_types.map(&:to_s).include?(value.to_s)
268
+ end
269
+
270
+ def tag_list_on(context, owner=nil)
271
+ var_name = context.to_s.singularize + "_list"
272
+ add_custom_context(context)
273
+ return instance_variable_get("@#{var_name}") unless instance_variable_get("@#{var_name}").nil?
274
+
275
+ if !owner && self.class.caching_tag_list_on?(context) and !(cached_value = cached_tag_list_on(context)).nil?
276
+ instance_variable_set("@#{var_name}", TagList.from(self["cached_#{var_name}"]))
277
+ else
278
+ instance_variable_set("@#{var_name}", TagList.new(*tags_on(context, owner).map(&:name)))
279
+ end
280
+ end
281
+
282
+ def tags_on(context, owner=nil)
283
+ if owner
284
+ opts = {:conditions => ["#{Tagging.table_name}.context = ? AND #{Tagging.table_name}.tagger_id = ? AND #{Tagging.table_name}.tagger_type = ?",
285
+ context.to_s, owner.id, owner.class.to_s]}
286
+ else
287
+ opts = {:conditions => ["#{Tagging.table_name}.context = ?", context.to_s]}
288
+ end
289
+ base_tags.find(:all, opts)
290
+ end
291
+
292
+ def cached_tag_list_on(context)
293
+ self["cached_#{context.to_s.singularize}_list"]
294
+ end
295
+
296
+ def set_tag_list_on(context,new_list, tagger=nil)
297
+ instance_variable_set("@#{context.to_s.singularize}_list", TagList.from_owner(tagger, new_list))
298
+ add_custom_context(context)
299
+ end
300
+
301
+ def tag_counts_on(context, options={})
302
+ self.class.tag_counts_on(context, options.merge(:id => self.id))
303
+ end
304
+
305
+ def related_tags_for(context, klass, options = {})
306
+ search_conditions = related_search_options(context, klass, options)
307
+
308
+ klass.find(:all, search_conditions)
309
+ end
310
+
311
+ def related_search_options(context, klass, options = {})
312
+ tags_to_find = self.tags_on(context).collect { |t| t.name }
313
+
314
+ exclude_self = "#{klass.table_name}.id != #{self.id} AND" if self.class == klass
315
+
316
+ { :select => "#{klass.table_name}.*, COUNT(#{Tag.table_name}.id) AS count",
317
+ :from => "#{klass.table_name}, #{Tag.table_name}, #{Tagging.table_name}",
318
+ :conditions => ["#{exclude_self} #{klass.table_name}.id = #{Tagging.table_name}.taggable_id AND #{Tagging.table_name}.taggable_type = '#{klass.to_s}' AND #{Tagging.table_name}.tag_id = #{Tag.table_name}.id AND #{Tag.table_name}.name IN (?)", tags_to_find],
319
+ :group => "#{klass.table_name}.id",
320
+ :order => "count DESC"
321
+ }.update(options)
322
+ end
323
+
324
+ def save_cached_tag_list
325
+ self.class.tag_types.map(&:to_s).each do |tag_type|
326
+ if self.class.send("caching_#{tag_type.singularize}_list?")
327
+ self["cached_#{tag_type.singularize}_list"] = send("#{tag_type.singularize}_list").to_s
328
+ end
329
+ end
330
+ end
331
+
332
+ def save_tags
333
+ (custom_contexts + self.class.tag_types.map(&:to_s)).each do |tag_type|
334
+ next unless instance_variable_get("@#{tag_type.singularize}_list")
335
+ owner = instance_variable_get("@#{tag_type.singularize}_list").owner
336
+ new_tag_names = instance_variable_get("@#{tag_type.singularize}_list") - tags_on(tag_type).map(&:name)
337
+ old_tags = tags_on(tag_type, owner).reject { |tag| instance_variable_get("@#{tag_type.singularize}_list").include?(tag.name) }
338
+
339
+ self.class.transaction do
340
+ base_tags.delete(*old_tags) if old_tags.any?
341
+ new_tag_names.each do |new_tag_name|
342
+ new_tag = Tag.find_or_create_with_like_by_name(new_tag_name)
343
+ Tagging.create(:tag_id => new_tag.id, :context => tag_type,
344
+ :taggable => self, :tagger => owner)
345
+ end
346
+ end
347
+ end
348
+
349
+ true
350
+ end
351
+
352
+ def reload_with_tag_list(*args)
353
+ self.class.tag_types.each do |tag_type|
354
+ self.instance_variable_set("@#{tag_type.to_s.singularize}_list", nil)
355
+ end
356
+
357
+ reload_without_tag_list(*args)
358
+ end
359
+ end
360
+ end
361
+ end
362
+ end