22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
# File 'lib/dm-tags/dm_tags.rb', line 22
def has_tags_on(*associations)
associations.flatten!
associations.uniq!
has n, :taggings, Tagging, :child_key => [ :taggable_id ], :taggable_type => self
before :destroy, :destroy_taggings
unless instance_methods(false).include?('destroy_taggings')
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def destroy_taggings
taggings.destroy!
end
RUBY
end
private :taggings, :taggings=, :destroy_taggings
extend(DataMapper::Tags::SingletonMethods)
associations.each do |association|
association = association.to_s
singular = DataMapper::Inflector.singularize(association)
class_eval <<-RUBY, __FILE__, __LINE__ + 1
property :frozen_#{singular}_list, Text
has n, :#{singular}_taggings, Tagging, :child_key => [ :taggable_id ], :taggable_type => self, :tag_context => '#{association}'
has n, :#{association}, Tag, :through => :#{singular}_taggings, :via => :tag, :order => [ :name ]
before :save, :update_#{association}
def #{singular}_list
@#{singular}_list ||= #{association}.map { |tag| tag.name }
end
def #{singular}_list=(string)
@#{singular}_list = string.to_s.split(',').map { |name| name.gsub(/[^\\w\\s_-]/i, '').strip }.uniq.sort
end
alias_method :#{singular}_collection=, :#{singular}_list=
def update_#{association}
self.#{association} = #{singular}_list.map do |name|
Tag.first_or_new(:name => name)
end
self.frozen_#{singular}_list = #{singular}_collection
end
##
# Helper methods to make setting tags easier
#
def #{singular}_collection
#{association}.map { |tag| tag.name }.join(', ')
end
##
# Like tag_collection= except it only add's tags
#
def add_#{singular}(string)
tag_names = string.to_s.split(',').map { |name| name.gsub(/[^\\w\\s_-]/i, '').strip }
@#{singular}_list = tag_names.concat(#{singular}_list).uniq.sort
end
RUBY
end
end
|