Method: AnnotationSecurity::Rule#extend_class

Defined in:
lib/annotation_security/policy/rule.rb

#extend_class(klass) ⇒ Object

Creates a method for a policy class that evaluates this rule

  • klass either @policy_class or its static partner



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/annotation_security/policy/rule.rb', line 78

def extend_class(klass) # :nodoc:

  # Arguments passed to AbstractPolicy#user_roles
  # * +role+ symbol identifying the role a user must have (or nil)
  # * +user_required+ if false, the rule will also be
  #                   evaluated if the user is nil
  user_args = "#{@as ? ":#@as" : 'nil'},#{requires_credential?}"

  # Actual logic of the rule
  rule_code = @proc ? code_for_proc : code_for_string

  # Arguments passed to RuleExecutionError#new if an error occured
  # while evaluating the rule
  # * +rule+ full name of the rule
  # * +proc+ true iif this rule is defined with a proc
  # * +ex+ the original exeption
  ex_args = "'#{full_name}',#{@proc ? true : false},$!"

  code = "def #@name(*args) \n"

  # If parameter :is is given, @user.is_{@is}? has to return true.
  # 
  code << "return false if @user.nil? || [email protected]_#@is?\n" if @is
  code << %{
    # __resource__ = @resource
    return user_roles(#{user_args}).any? do |__user__|
      #{rule_code}
    end
  rescue StandardError
    raise $! if $!.is_a? AnnotationSecurity::SecurityError
    raise AnnotationSecurity::RuleExecutionError.new(#{ex_args})
  end}
  klass.class_eval(code)
  self
end