Files
componentowl-rails-archive/app/models/bmt_license_key.rb

47 lines
1.0 KiB
Ruby

class BmtLicenseKey
attr_accessor :license_key, :error
ATTEMPTS = 5
def initialize
@attempt = 0
end
def generate!
@attempt += 1
self.license_key = Array.new(16) { rand(2) == 0 ? (rand(90-65) + 65).chr : (rand(7) + 50).chr }.join.gsub(/[IO]/, "X")
existing_license_key = Order.find_by_license_key(license_key)
if existing_license_key && @attempt < ATTEMPTS
generate!
elsif existing_license_key && @attempt == ATTEMPTS
attempts_failed!
end
license_key
end
def attempts_failed!
self.license_key = nil
@attempts_failed = true
end
def attempts_failed?
@attempts_failed == true
end
def to_xml(options = {})
xml = Builder::XmlMarkup.new
xml.instruct!
xml.response do
xml.registrationkey do
if attempts_failed?
xml.errorcode 1
xml.errormessage "The attempts to generate unique license key failed (#{ATTEMPTS} times)."
else
xml.keydata license_key
end
end
end
end
end