Class: Hiiro::Tags

Inherits:
Object
  • Object
show all
Defined in:
lib/hiiro/tags.rb

Overview

Shared tag store, keyed by namespace (e.g. :branch, :task). Delegates to Hiiro::Tag internally; maintains tags.yml as a backup.

Constant Summary collapse

FILE =
Hiiro::Config.path('tags.yml')

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(namespace, fs: Hiiro::Effects::Filesystem.new) ⇒ Tags

Returns a new instance of Tags.



102
103
104
105
# File 'lib/hiiro/tags.rb', line 102

def initialize(namespace, fs: Hiiro::Effects::Filesystem.new)
  @namespace = namespace.to_s
  @fs = fs
end

Class Method Details

.badges(tags) ⇒ Object

Formats a tag array as colored badges for terminal output.



153
154
155
# File 'lib/hiiro/tags.rb', line 153

def self.badges(tags)
  Array(tags).map { |t| "\e[30;104m#{t}\e[0m" }.join(' ')
end

Instance Method Details

#add(key, *tags) ⇒ Object

Adds tags to a key (idempotent). Returns the new tag array.



113
114
115
116
117
118
119
120
121
122
# File 'lib/hiiro/tags.rb', line 113

def add(key, *tags)
  tags.each do |tag_name|
    Hiiro::Tag.find_or_create(
      name: tag_name.to_s,
      taggable_type: type_name,
      taggable_id: key.to_s
    ) { |t| t.created_at = Time.now.iso8601 }
  end
  get(key).tap { save_yaml_backup }
end

#allObject

Returns the full { key => [tags] } hash for this namespace.



139
140
141
142
143
144
145
# File 'lib/hiiro/tags.rb', line 139

def all
  Hiiro::Tag.where(taggable_type: type_name)
    .each_with_object({}) do |t, h|
      h[t.taggable_id] ||= []
      h[t.taggable_id] << t.name
    end
end

#get(key) ⇒ Object

Returns the tag array for a given key ([] if none).



108
109
110
# File 'lib/hiiro/tags.rb', line 108

def get(key)
  Hiiro::Tag.where(taggable_type: type_name, taggable_id: key.to_s).map(&:name)
end

#known_tagsObject

Returns all distinct tag values used in this namespace.



148
149
150
# File 'lib/hiiro/tags.rb', line 148

def known_tags
  Hiiro::Tag.where(taggable_type: type_name).distinct.pluck(:name).sort
end

#remove(key, *tags) ⇒ Object

Removes specific tags from a key. Pass no tags to clear all.



125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/hiiro/tags.rb', line 125

def remove(key, *tags)
  if tags.empty?
    Hiiro::Tag.where(taggable_type: type_name, taggable_id: key.to_s).delete
  else
    Hiiro::Tag.where(
      taggable_type: type_name,
      taggable_id: key.to_s,
      name: tags.map(&:to_s)
    ).delete
  end
  save_yaml_backup
end