|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require "forwardable" |
| 4 | + |
| 5 | +module ActiveFunction |
| 6 | + class ParameterMissingError < Error |
| 7 | + MESSAGE_TEMPLATE = "Missing parameter: %s" |
| 8 | + |
| 9 | + attr_reader :message |
| 10 | + |
| 11 | + def initialize(param) |
| 12 | + MESSAGE_TEMPLATE % param |
| 13 | + end |
| 14 | + end |
| 15 | + |
| 16 | + class UnpermittedParameterError < Error |
| 17 | + MESSAGE_TEMPLATE = "Unpermitted parameter: %s" |
| 18 | + |
| 19 | + attr_reader :message |
| 20 | + |
| 21 | + def initialize(param) |
| 22 | + MESSAGE_TEMPLATE % param |
| 23 | + end |
| 24 | + end |
| 25 | + |
| 26 | + module Functions |
| 27 | + module StrongParameters |
| 28 | + def params |
| 29 | + @_params ||= Parameters.new(@request) |
| 30 | + end |
| 31 | + |
| 32 | + class Parameters |
| 33 | + extend Forwardable |
| 34 | + def_delegators :@parameters, :each, :map |
| 35 | + include Enumerable |
| 36 | + |
| 37 | + def initialize(parameters, permitted: false) |
| 38 | + @parameters = parameters |
| 39 | + @permitted = permitted |
| 40 | + end |
| 41 | + |
| 42 | + def [](attribute) |
| 43 | + nested_attribute(parameters[attribute]) |
| 44 | + end |
| 45 | + |
| 46 | + def require(attribute) |
| 47 | + value = self[attribute] |
| 48 | + |
| 49 | + raise ParameterMissingError, attribute if value.nil? |
| 50 | + |
| 51 | + value |
| 52 | + end |
| 53 | + |
| 54 | + def permit(*attributes) |
| 55 | + pparams = {} |
| 56 | + |
| 57 | + attributes.each do |attribute| |
| 58 | + if attribute.is_a? Hash |
| 59 | + attribute.each do |k, v| |
| 60 | + pparams[k] = process_nested(self[k], :permit, v) |
| 61 | + end |
| 62 | + else |
| 63 | + next unless parameters.key?(attribute) |
| 64 | + |
| 65 | + pparams[attribute] = self[attribute] |
| 66 | + end |
| 67 | + end |
| 68 | + |
| 69 | + Parameters.new(pparams, permitted: true) |
| 70 | + end |
| 71 | + |
| 72 | + def to_h |
| 73 | + raise UnpermittedParameterError, parameters.keys unless @permitted |
| 74 | + |
| 75 | + parameters.transform_values { |_1| process_nested(_1, :to_h) } |
| 76 | + end |
| 77 | + |
| 78 | + private |
| 79 | + |
| 80 | + def nested_attribute(attribute) |
| 81 | + if attribute.is_a? Hash |
| 82 | + Parameters.new(attribute) |
| 83 | + elsif attribute.is_a?(Array) && attribute[0].is_a?(Hash) |
| 84 | + attribute.map { |_1| Parameters.new(_1) } |
| 85 | + else |
| 86 | + attribute |
| 87 | + end |
| 88 | + end |
| 89 | + |
| 90 | + def process_nested(attribute, method, options = []) |
| 91 | + if attribute.is_a? Parameters |
| 92 | + attribute.send(method, *options) |
| 93 | + elsif attribute.is_a?(Array) && attribute[0].is_a?(Parameters) |
| 94 | + attribute.map { |_1| _1.send(method, *options) } |
| 95 | + else |
| 96 | + attribute |
| 97 | + end |
| 98 | + end |
| 99 | + |
| 100 | + attr_reader :parameters |
| 101 | + end |
| 102 | + end |
| 103 | + end |
| 104 | +end |
0 commit comments