Class: Tag::Store

Inherits:
Object
  • Object
show all
Defined in:
lib/tag/store.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model = nil) ⇒ Store

Returns a new instance of Store.



10
11
12
13
14
# File 'lib/tag/store.rb', line 10

def initialize(model = nil)
  model ||= ENV['TAG_MODEL'] || 'default'
  @file = File.join(Tag.home, "#{model}.yml")
  @hash = File.exists?(@file) ? YAML.load_file(@file) : {}
end

Class Method Details

.modelsObject



6
7
8
# File 'lib/tag/store.rb', line 6

def self.models
  Dir["#{Tag.home}/*.yml"].map {|file| file[%r{([^/]+).yml$}, 1] }.sort
end

Instance Method Details

#delete_tags(*tags) ⇒ Object



63
64
65
66
# File 'lib/tag/store.rb', line 63

def delete_tags(*tags)
  tags.each {|tag| @hash.delete(tag) }
  save
end

#itemsObject



68
69
70
71
72
73
74
75
76
# File 'lib/tag/store.rb', line 68

def items
  @hash.each_with_object({}) do |(tag,items),acc|
    items.each do |item|
      (acc[item] ||= []) << tag
    end
  end.sort_by {|e| e[0] }.map do |k,v|
    "#{k}\t#{v.uniq.join(', ')}"
  end
end

#list(tag) ⇒ Object



48
49
50
51
# File 'lib/tag/store.rb', line 48

def list(tag)
  @hash[tag] ||= []
  @hash[tag]
end

#list_tagsObject



53
54
55
# File 'lib/tag/store.rb', line 53

def list_tags
  @hash.keys.sort
end

#multi_remove_tag(items, tags) ⇒ Object



34
35
36
37
38
39
40
41
# File 'lib/tag/store.rb', line 34

def multi_remove_tag(items, tags)
  tags.each do |tag|
    items.each do |item|
      remove_tag(item, tag)
    end
  end
  save
end

#multi_tag(items, tags) ⇒ Object



25
26
27
28
29
30
31
32
# File 'lib/tag/store.rb', line 25

def multi_tag(items, tags)
  tags.each do |tag|
    items.each do |item|
      tag(item, tag)
    end
  end
  save
end

#remove_tag(item, tag) ⇒ Object



43
44
45
46
# File 'lib/tag/store.rb', line 43

def remove_tag(item, tag)
  @hash[tag] ||= []
  @hash[tag].delete item
end

#saveObject



16
17
18
# File 'lib/tag/store.rb', line 16

def save
  File.open(@file, 'w') {|f| f.write(@hash.to_yaml) }
end

#tag(item, tag) ⇒ Object



20
21
22
23
# File 'lib/tag/store.rb', line 20

def tag(item, tag)
  @hash[tag] ||= []
  @hash[tag] << item
end

#treeObject



57
58
59
60
61
# File 'lib/tag/store.rb', line 57

def tree
  list_tags.map {|tag|
    ["#{tag}", list(tag).map {|t| "    #{t}" }]
  }.flatten
end