11class Subscription < ApplicationRecord
2- self . inheritance_column = 'sti_type'
3-
42 include CommunityRelated
53 include Timestamped
64
5+ self . inheritance_column = 'sti_type'
6+
7+ BASE_TYPES = [ 'all' , 'tag' , 'user' , 'interesting' , 'category' ] . freeze
8+ MOD_ONLY_TYPES = [ 'moderators' ] . freeze
9+ TYPES = ( BASE_TYPES + MOD_ONLY_TYPES ) . freeze
10+ QUALIFIED_TYPES = [ 'category' , 'tag' , 'user' ] . freeze
11+
712 belongs_to :user
813
9- validates :type , presence : true , inclusion : [ 'all' , 'tag' , 'user' , 'interesting' , 'category' , 'moderators' ]
14+ validates :type , presence : true , inclusion : TYPES
1015 validates :frequency , numericality : { minimum : 1 , maximum : 90 }
1116
1217 validate :qualifier_presence
1318
19+ # Gets a list of subscription types available to a given user
20+ # @param user [User] user to check type access for
21+ # @return [Array<String>] list of available types
22+ def self . types_accessible_to ( user )
23+ user . at_least_moderator? ? TYPES : BASE_TYPES
24+ end
25+
1426 def questions
1527 case type
1628 when 'all'
@@ -36,10 +48,39 @@ def questions
3648 end &.order ( created_at : :desc ) &.limit ( 25 )
3749 end
3850
51+ # Is the subscription's type qualified (bound to an entity)?
52+ # @param type [String] type to check
53+ # @return [Boolean] check result
54+ def qualified?
55+ QUALIFIED_TYPES . include? ( type )
56+ end
57+
58+ # Gets entity bound to the subscription through qualifier, if any
59+ # @return [Category, Tag, User, nil]
60+ def qualifier_entity
61+ if qualified? && qualifier . present?
62+ model = type . singularize . classify . constantize
63+ tag? ? model . find_by ( name : qualifier ) : model . find ( qualifier )
64+ end
65+ end
66+
67+ # Gets name of the entity bound to the subscription through qualifier, if any
68+ # @return [String]
69+ def qualifier_name
70+ qualifier_entity &.name || qualifier
71+ end
72+
73+ # Predicates for each of the available type (f.e., user?)
74+ TYPES . each do |type_name |
75+ define_method "#{ type_name } ?" do
76+ type == type_name
77+ end
78+ end
79+
3980 private
4081
4182 def qualifier_presence
42- return unless [ 'tag' , 'user' , 'category' ] . include? type
83+ return unless qualified?
4384
4485 if type == 'tag' && ( qualifier . blank? || Tag . find_by ( name : qualifier ) . nil? )
4586 errors . add ( :qualifier , 'must provide a valid tag name for tag subscriptions' )
0 commit comments