lib/egn/generator.rb in egn-0.2.0 vs lib/egn/generator.rb in egn-0.4.0
- old
+ new
@@ -1,46 +1,49 @@
+# Generates a random valid EGN
module Egn
module Generator
- PARITY_WEIGHTS = [2,4,8,5,10,9,7,3,6]
+ # The generated EGN will be completely random if no opitons are given.
+ # options is a hash that may have the following keys: :year, :month and :date
+ def self.generate(options={})
+ date = Util.time_rand
- def self.egn
- date = time_rand
- year = date.year
- mon = date.month
- day = date.day
+ options = {
+ year: date.year,
+ month: date.month,
+ day: date.day
+ }.merge(options)
- cent = year - (year % 100)
+ validate!(options)
+
+ century = options[:year] - (options[:year] % 100)
sex = Random.rand(1..2)
- if cent == 1800
- mon += 20
- elsif cent == 2000
- mon += 40
+ if century == 1800
+ options[:month] += 20
+ elsif century == 2000
+ options[:month] += 40
end
region = Random.rand(0..999)
if sex == 1 && (region %2 != 0)
region -= 1
elsif sex == 2 && (region % 2 == 0)
region += 1
end
- final_year = year - cent
- egn = final_year.to_s.rjust(2, '0') + mon.to_s.rjust(2, '0') + day.to_s.rjust(2,'0') + region.to_s.rjust(3,'0')
+ final_year = options[:year] - century
+ egn = final_year.to_s.rjust(2, '0') + options[:month].to_s.rjust(2, '0') + options[:day].to_s.rjust(2,'0') + region.to_s.rjust(3,'0')
- return egn + egn_checksum(egn).to_s
+ return egn + Util.egn_checksum(egn).to_s
end
- def self.egn_checksum(egn)
- sum = egn.split('').map(&:to_i).zip(PARITY_WEIGHTS).map { |n| n.reduce(:*) }.reduce(:+)
-
- rest = sum % 11
- rest < 10 ? rest : 0
+ # Check if the options contain a date that is valid and be turned into an EGN
+ def self.validate!(options)
+ raise ArgumentError, "Year out of bounds" unless (1800..2099).include?(options[:year])
+ raise ArgumentError, "Month out of bounds" unless (1..12).include?(options[:month])
+ raise ArgumentError, "Day out of bounds" unless (1..31).include?(options[:day])
end
- def self.time_rand(from = 0.0, to = Time.now)
- Time.at(from + rand * (to.to_f - from.to_f))
- end
end
end