Guest User

Untitled

a guest
Feb 19th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. module ActiveRecord
  2. module Acts #:nodoc:
  3. module Taggable #:nodoc:
  4. def self.included(base)
  5. base.extend(ClassMethods)
  6. end
  7.  
  8. module ClassMethods
  9. def acts_as_taggable(options = {})
  10. write_inheritable_attribute(:acts_as_taggable_options, {
  11. :taggable_type => ActiveRecord::Base.send(:class_name_of_active_record_descendant, self).to_s,
  12. :from => options[:from]
  13. })
  14.  
  15. class_inheritable_reader :acts_as_taggable_options
  16.  
  17. has_many :taggings, :as => :taggable, :dependent => true
  18. has_many :tags, :through => :taggings
  19.  
  20. include ActiveRecord::Acts::Taggable::InstanceMethods
  21. extend ActiveRecord::Acts::Taggable::SingletonMethods
  22. end
  23. end
  24.  
  25. module SingletonMethods
  26. def find_tagged_with(*list)
  27. find_by_sql([
  28. "SELECT #{table_name}.* FROM #{table_name}, tags, taggings " +
  29. "WHERE #{table_name}.#{primary_key} = taggings.taggable_id " +
  30. "AND taggings.taggable_type = ? " +
  31. "AND taggings.tag_id = tags.id AND tags.name IN (?)",
  32. acts_as_taggable_options[:taggable_type], list
  33. ]).uniq
  34. end
  35.  
  36. def find_tagged_with_all (*list)
  37. tagged = list.collect { |name| find_tagged_with(name) }
  38. tagged.inject { |items, tagged| items & tagged }
  39. end
  40.  
  41. def tags_with_count
  42. Tagging.count :conditions => ["taggable_type = ?", acts_as_taggable_options[:taggable_type]], :joins => "LEFT JOIN tags ON taggings.tag_id=tags.id", :group => 'tags.name', :order => 'tags.name'
  43. end
  44. end
  45.  
  46. module InstanceMethods
  47. def tag_with(list)
  48. Tag.transaction do
  49. self.taggings.destroy_all
  50.  
  51. Tag.parse(list).each do |name|
  52. if acts_as_taggable_options[:from]
  53. send(acts_as_taggable_options[:from]).tags.find_or_create_by_name(name).on(self)
  54. else
  55. Tag.find_or_create_by_name(name).on(self)
  56. end
  57. end
  58. end
  59. end
  60.  
  61. def tag_list
  62. tags.collect { |tag| tag.name.include?(" ") ? "\"#{tag.name}\"" : tag.name }.join(" ")
  63. end
  64. end
  65. end
  66. end
  67. end
Add Comment
Please, Sign In to add comment