| Total Complexity | 17 | 
| Total Lines | 80 | 
| Duplicated Lines | 0 % | 
| Changes | 1 | ||
| Bugs | 0 | Features | 0 | 
| 1 | # frozen_string_literal: true | ||
| 10 | class Policy | ||
| 11 | include Comparable | ||
| 12 | include Mixin::Entity | ||
| 13 | |||
| 14 | def self.values | ||
| 15 | %i[none edit manage] | ||
| 16 | end | ||
| 17 | |||
| 18 | attribute :value, Symbol, values: values, default: :none | ||
| 19 | |||
| 20 | normalizer_block do |entity, *| | ||
| 21 | entity.value | ||
| 22 | end | ||
| 23 | |||
| 24 | denormalizer_block do |input, type, context, &block| | ||
| 25 | if input.is_a?(String) || input.is_a?(Symbol) | ||
| 26 |               input = { value: input } | ||
| 27 | end | ||
| 28 | block.call(input, type, context) | ||
| 29 | end | ||
| 30 | |||
| 31 | def initialize(value = :none) | ||
| 32 | self.value = value | ||
| 33 | end | ||
| 34 | |||
| 35 | NONE = new(:none) | ||
| 36 | EDIT = new(:edit) | ||
| 37 | MANAGE = new(:manage) | ||
| 38 | |||
| 39 | def self.wrap(value) | ||
| 40 | return value if value.is_a?(Policy) | ||
| 41 | condition = value.is_a?(String) || value.is_a?(Symbol) | ||
| 42 | if condition && Policy.const_defined?(value.upcase) | ||
| 43 | return Policy.const_get(value.upcase) | ||
| 44 | end | ||
| 45 |             raise ArgumentError, "Invalid policy value: #{value}" | ||
| 46 | end | ||
| 47 | |||
| 48 | def edit? | ||
| 49 | self > NONE | ||
| 50 | end | ||
| 51 | |||
| 52 | def create? | ||
| 53 | self > NONE | ||
| 54 | end | ||
| 55 | |||
| 56 | def remove? | ||
| 57 | self == MANAGE | ||
| 58 | end | ||
| 59 | |||
| 60 | def manage? | ||
| 61 | self == MANAGE | ||
| 62 | end | ||
| 63 | |||
| 64 | def nothing? | ||
| 65 | self == NONE | ||
| 66 | end | ||
| 67 | |||
| 68 | def <=>(other) | ||
| 69 | other = Policy.wrap(other) | ||
| 70 | unless other.is_a?(Policy) | ||
| 71 |               raise ArgumentError, "Invalid input: #{other.inspect}" | ||
| 72 | end | ||
| 73 | values = self.class.values | ||
| 74 | values.index(value) - values.index(other.value) | ||
| 75 | end | ||
| 76 | |||
| 77 | def eq?(other) | ||
| 78 | return false unless other.is_a?(Policy) | ||
| 79 | other.value == @value | ||
| 80 | end | ||
| 81 | |||
| 82 | def ==(other) | ||
| 83 | eq?(other) | ||
| 84 | end | ||
| 85 | |||
| 86 | def to_s | ||
| 87 | value.to_s | ||
| 88 | end | ||
| 89 | end | ||
| 90 | end | ||
| 94 |