# encoding: utf-8 module ServiceObjects module Helpers # Features for service parameters declaration # # @note # A target class should be **extended** by the module module Parameterized # Whitelists {.new} options assigned to params # # Mutates the current class by adding the corresponding attribute # for every parameter. # # @example Whitelists options # class AddFoo # extend ServiceObjects::Helpers::Parameterized # # allows_params :foo # end # # service = AddFoo.new foo: "foo", bar: "baz" # service.params # => { foo: "foo" } # # @example Adds attributes as aliases to corresponding params # class AddFoo # extend ServiceObjects::Helpers::Parameterized # # allows_params :foo # end # # service = AddFoo.new foo: "foo" # service.foo # => "foo" # # service.params[:foo] = "bar" # service.foo # => "bar" # # service.foo = "baz" # service.foo # => "baz" # service.params[:foo] # => "baz" # # @param [Array<#to_sym>] list # # @return [Array] # the list of arguments def allows_params(*list) @whitelist = list.flatten.map(&:to_sym).freeze __attr_params__ whitelist end private # @!parse include ServiceObjects::Helpers::Parameters def self.extended(klass) klass.include Parameters super end def __attr_params__ whitelist.each(&method(:__attr_param_accessor__)) end def __attr_param_accessor__(name) __attr_param_reader__ name __attr_param_writer__ name end def __attr_param_reader__(name) define_method(name) { params[name] } end def __attr_param_writer__(name) define_method("#{ name }=") { |value| params[name] = value } end end # module Parameters end # module Helpers end # module ServiceObjects