aboutsummaryrefslogtreecommitdiffstats
path: root/app/controllers/concerns/feature_checker.rb
blob: 5e102ef1bdb091915dc8753786b559a39dc79972 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# Check availability of optional features
#
# In your controller, use :
#
#   requires_feature :test
#   requires_feature :test, only: [:show]
#
# In your view, use :
#
#   has_feature? :test
#
module FeatureChecker
  extend ActiveSupport::Concern

  module ClassMethods
    def requires_feature(feature, options = {})
      before_action options do
        check_feature! feature
      end
    end
  end

  included do
    helper_method :has_feature?
  end

  protected

  def has_feature?(*features)
    return false unless current_organisation

    features.all? do |feature|
      current_organisation.has_feature? feature
    end
  end

  def check_feature!(*features)
    unless has_feature?(*features)
      raise NotAuthorizedError, "Feature not autorized"
    end
  end

  class NotAuthorizedError < StandardError; end
end