Module: Sequel::Plugins::Tags::InstanceMethods

Defined in:
lib/cortex_reaver/support/tags.rb

Instance Method Summary collapse

Instance Method Details

#after_saveObject

If tags have changed, make sure to update those tags’ counts.



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/cortex_reaver/support/tags.rb', line 42

def after_save
  return false if super == false

  if @added_tags
    @added_tags.each do |tag|
      tag.count += 1
      tag.save
    end
    @removed_tags.each do |tag|
      tag.count -= 1
      tag.save
    end
  end

  true
end

#before_destroyObject

Remove tags on deletion



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/cortex_reaver/support/tags.rb', line 60

def before_destroy
  return false unless super

  tags.each do |tag|
    tag.count -= 1
    if tag.count == 0
      tag.destroy
    else
      tag.save
    end
  end
  remove_all_tags

  true
end

Finds related models by tags.



77
78
79
80
81
82
83
84
85
86
# File 'lib/cortex_reaver/support/tags.rb', line 77

def related_by_tags
  # Find map between this model and tags, e.g. pages_tags
  reflection = self.association_reflection(:tags)
  map = reflection[:join_table]
  own_id = reflection[:left_key]
  tags = self.tags.map(:id)
  self.class.filter(
    CortexReaver.db[map].filter(:tag_id => tags).group_and_count(own_id).reverse.map(:photograph_ids)
  )
end

#tags=(tags) ⇒ Object

Set tags from a string, or array of tags. Finds existing tags or creates new ones. Also updates tag counts.



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/cortex_reaver/support/tags.rb', line 90

def tags=(tags)
  if tags.kind_of? String
    tags = tags.squeeze(',').split(',').map do |title|
      title.strip!
      if title.blank?
        # Do nothing
        tag = nil
      else
        # Look up existing tag
        tag = CortexReaver::Tag[:title => title]
        # Or create new one
        tag ||= CortexReaver::Tag.create(:title => title, :name => CortexReaver::Tag.canonicalize(title))
        unless tag
          # Everything failed
          raise RuntimeError.new("couldn't find or create tag for #{title}")
        end
      end
      tag
    end
  end

  unless tags.respond_to? :each
    raise ArgumentError.new("Needed a string or Enumerable of Tags, got #{tags.class}")
  end

  # Get rid of empty tags
  tags.reject do |tag|
    tag.nil?
  end
  tags.uniq!

  # Find which tags to change. Their counts are updated by an after_save
  # callback.
  old_tags = self.tags
  @removed_tags = old_tags - tags
  @added_tags = tags - old_tags

  # Change own tags
  remove_all_tags
  tags.each do |tag|
    add_tag tag
  end
end