]> nos-oignons.net Git - gestion-adh.git/blob - lib/nos_oignons/subscriptions.rb
de4ddf0607c2a47f80108b8346ceb7f70ffb7784
[gestion-adh.git] / lib / nos_oignons / subscriptions.rb
1 require 'safe_yaml'
2 SafeYAML::OPTIONS[:default_mode] = :safe
3
4 module NosOignons
5   SUBSCRIPTIONS_ROOT = 'Membres'
6   SUBSCRIPTION_FIELDS = [:name, :address, :email, :membership_fee_paid_on]
7   SUBSCRIPTION_MANDATORY_FIELDS = [:name, :email]
8
9   class Subscription < Struct.new(*SUBSCRIPTION_FIELDS)
10     class << self
11       def all
12         Dir.glob("#{SUBSCRIPTIONS_ROOT}/*.mdwn").sort.collect do |file|
13           subscription_id = File.basename(file).gsub(/\.mdwn$/, '')
14           Subscription.new(subscription_id)
15         end
16       end
17
18       def filename_for_id(subscription_id)
19         "Membres/%06d.mdwn" % subscription_id
20       end
21
22       def read_from_git(ref, file)
23         IO.popen(['git', 'show', "#{ref}:#{file}"]) do |f|
24           subscription_id = File.basename(file).gsub(/\.mdwn$/, '')
25           Subscription.new(subscription_id, f.read)
26         end
27       end
28     end
29
30     attr_reader :subscription_id
31
32     def initialize(subscription_id, page_content=nil)
33       unless subscription_id =~ /\A\d{6}\z/
34         raise ArgumentError.new('bad subscription id format')
35       end
36       @subscription_id = subscription_id
37       unless page_content
38         page_content = File.open(Subscription.filename_for_id(subscription_id)).read
39       end
40       unless page_content.start_with?("---\n")
41         raise ArgumentError.new('content is not a proper YAML document')
42       end
43       data = YAML.load(page_content)
44       SUBSCRIPTION_FIELDS.each do |field|
45         self[field] = data[field.to_s]
46       end
47       # Immutability for the win
48       SUBSCRIPTION_FIELDS.each do |field|
49         instance_eval{ undef :"#{field}=" }
50       end
51       SUBSCRIPTION_MANDATORY_FIELDS.each do |sym|
52         raise ArgumentError.new('missing mandatory fields') unless self[sym]
53       end
54       if membership_fee_paid_on && !membership_fee_paid_on.is_a?(Date)
55         raise ArgumentError.new('membership_fee_paid_on is not a date')
56       end
57     end
58
59     def up_to_date?
60       now = Time.now
61       last_year = Time.new(now.year - 1, now.month, now.day).to_date
62       membership_fee_paid_on && last_year < membership_fee_paid_on
63     end
64   end
65 end