Method: Zold::Copies#add
- Defined in:
- lib/zold/copies.rb
#add(content, host, port, score, time = Time.now) ⇒ Object
Returns the name of the copy
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 |
# File 'lib/zold/copies.rb', line 92 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.negative? 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.negative? Futex.new(file, log: @log).open do FileUtils.mkdir_p(@dir) list = load target = list.find do |s| f = File.join(@dir, "#{s[:name]}#{Copies::EXT}") File.exist?(f) && IO.read(f) == content end if target.nil? max = DirItems.new(@dir).fetch .select { |f| File.basename(f, Copies::EXT) =~ /^[0-9]+$/ } .map(&:to_i) .max max = 0 if max.nil? name = (max + 1).to_s IO.write(File.join(@dir, "#{name}#{Copies::EXT}"), 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) name end end |