]> git.openstreetmap.org Git - rails.git/blob - app/models/user_block.rb
Split come changset display logic into a helper
[rails.git] / app / models / user_block.rb
1 class UserBlock < ActiveRecord::Base
2   validate :moderator_permissions
3
4   belongs_to :user, :class_name => "User", :foreign_key => :user_id
5   belongs_to :creator, :class_name => "User", :foreign_key => :creator_id
6   belongs_to :revoker, :class_name => "User", :foreign_key => :revoker_id
7   
8   after_initialize :set_defaults
9
10   PERIODS = USER_BLOCK_PERIODS
11
12   ##
13   # scope to match active blocks
14   def self.active
15     self.where("needs_view or ends_at > ?", Time.now.getutc)
16   end
17
18   ##
19   # return a renderable version of the reason text.
20   def reason
21     RichText.new(read_attribute(:reason_format), read_attribute(:reason))
22   end
23
24   ##
25   # returns true if the block is currently active (i.e: the user can't
26   # use the API).
27   def active?
28     needs_view or ends_at > Time.now.getutc
29   end
30
31   ##
32   # revokes the block, allowing the user to use the API again. the argument
33   # is the user object who is revoking the ban.
34   def revoke!(revoker)
35     update_attributes(
36       :ends_at => Time.now.getutc(),
37       :revoker_id => revoker.id,
38       :needs_view => false
39     )
40   end
41
42 private
43
44   ##
45   # set default values for new records.
46   def set_defaults
47     self.reason_format = "markdown" unless self.attribute_present?(:reason_format)
48   end
49
50   ##
51   # validate that only moderators are allowed to change the
52   # block. this should be caught and dealt with in the controller,
53   # but i've also included it here just in case.
54   def moderator_permissions
55     errors.add(:base, I18n.t('user_block.model.non_moderator_update')) if creator_id_changed? and !creator.moderator?
56     errors.add(:base, I18n.t('user_block.model.non_moderator_revoke')) unless revoker_id.nil? or revoker.moderator?
57   end
58 end