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.
32 33 34 |
# File 'lib/zold/copies.rb', line 32 def initialize(dir) @dir = dir end |
Instance Method Details
#add(content, host, port, score, time = Time.now) ⇒ Object
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 91 |
# File 'lib/zold/copies.rb', line 57 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) && AtomicFile.new(f).read == 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 AtomicFile.new(File.join(@dir, name)).write(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
93 94 95 96 97 98 99 100 101 102 103 104 105 |
# File 'lib/zold/copies.rb', line 93 def all load.group_by { |s| s[:name] }.map do |name, scores| { name: name, host: scores[0][:host], port: scores[0][:port], 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
44 45 46 47 48 49 50 51 |
# File 'lib/zold/copies.rb', line 44 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
53 54 55 |
# File 'lib/zold/copies.rb', line 53 def remove(host, port) save(load.reject { |s| s[:host] == host && s[:port] == port }) end |
#root ⇒ Object
36 37 38 |
# File 'lib/zold/copies.rb', line 36 def root File.join(@dir, '..') end |
#to_s ⇒ Object
40 41 42 |
# File 'lib/zold/copies.rb', line 40 def to_s File.basename(@dir) end |