Class: Zold::Copies
- Inherits:
-
Object
- Object
- Zold::Copies
- Defined in:
- lib/zold/copies.rb
Overview
All copies
Instance Method Summary collapse
- #add(content, host, port, score, time = Time.now) ⇒ Object
- #all ⇒ Object
- #clean ⇒ Object
-
#initialize(dir) ⇒ Copies
constructor
A new instance of Copies.
- #remove(host, port) ⇒ Object
- #root ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(dir) ⇒ Copies
Returns a new instance of Copies.
31 32 33 |
# File 'lib/zold/copies.rb', line 31 def initialize(dir) @dir = dir end |
Instance Method Details
#add(content, host, port, score, time = Time.now) ⇒ Object
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 89 90 |
# File 'lib/zold/copies.rb', line 56 def add(content, host, port, score, time = Time.now) raise "Content can't be empty" if content.empty? raise 'TCP port must be of type Integer' unless port.is_a?(Integer) raise "TCP port can't be negative: #{port}" if port < 0 raise 'Time must be of type Time' unless time.is_a?(Time) raise "Time must be in the past: #{time}" if time > Time.now raise 'Score must be Integer' unless score.is_a?(Integer) raise "Score can't be negative: #{score}" if score < 0 FileUtils.mkdir_p(@dir) list = load target = list.find do |s| f = File.join(@dir, s[:name]) File.exist?(f) && File.read(f) == content end if target.nil? max = Dir.new(@dir) .select { |f| f =~ /^[0-9]+$/ } .map(&:to_i) .max max = 0 if max.nil? name = (max + 1).to_s File.write(File.join(@dir, name), content) else name = target[:name] end list.reject! { |s| s[:host] == host && s[:port] == port } list << { name: name, host: host, port: port, score: score, time: time } save(list) end |
#all ⇒ Object
92 93 94 95 96 97 98 99 100 101 102 |
# File 'lib/zold/copies.rb', line 92 def all load.group_by { |s| s[:name] }.map do |name, scores| { name: name, path: File.join(@dir, name), score: scores.select { |s| s[:time] > Time.now - 24 * 60 * 60 } .map { |s| s[:score] } .inject(&:+) || 0 } end.select { |c| File.exist?(c[:path]) } end |
#clean ⇒ Object
43 44 45 46 47 48 49 50 |
# File 'lib/zold/copies.rb', line 43 def clean list = load list.reject! { |s| s[:time] < Time.now - 24 * 60 * 60 } save(list) Dir.new(@dir).select { |f| f =~ /^[0-9]+$/ }.each do |f| File.delete(File.join(@dir, f)) if list.find { |s| s[:name] == f }.nil? end end |
#remove(host, port) ⇒ Object
52 53 54 |
# File 'lib/zold/copies.rb', line 52 def remove(host, port) save(load.reject { |s| s[:host] == host && s[:port] == port }) end |
#root ⇒ Object
35 36 37 |
# File 'lib/zold/copies.rb', line 35 def root File.join(@dir, '..') end |
#to_s ⇒ Object
39 40 41 |
# File 'lib/zold/copies.rb', line 39 def to_s File.basename(@dir) end |