summaryrefslogtreecommitdiff
path: root/certs/app/models/cert.rb
blob: 9a6c98dcfd935b2fe7fd374db64511dcd8837b3c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Cert < CouchRest::Model::Base

  use_database 'client_certificates'

  timestamps!

  property :random, Float, :accessible => false

  before_validation :set_random, :attach_zip, :on => :create

  validates :random, :presence => true,
    :numericality => {:greater_than => 0, :less_than => 1}

  validates :zip_attachment, :presence => true

  design do
    view :by_random
  end

  class << self
    def sample
      self.by_random.startkey(rand).first || self.by_random.first
    end

    def pick_from_pool
      cert = self.sample || self.create!
      cert.destroy
      return cert
    rescue RESOURCE_NOT_FOUND
      retry if Cert.by_random.count > 0
      raise RECORD_NOT_FOUND
    end

  end

  def set_random
    self.random = rand
  end

  def attach_zip
    file = File.open(Rails.root.join("config", "cert"))
    self.create_attachment :file => file, :name => zipname
  end

  def zipname
    'cert.txt'
  end

  def zip_attachment
    attachments[zipname]
  end

  def zipped
    read_attachment(zipname)
  end

end