Sha256: 388f1bbbbe5de258da9442b9d8622fe499ae63f066fce65e4b2406805893b669

Contents?: true

Size: 1.59 KB

Versions: 3

Compression:

Stored size: 1.59 KB

Contents

# encoding: utf-8

module ServiceObjects

  module Helpers

    # Features for whitelisting service options
    #
    # @note
    #   A target class should **include** the module
    module Parameters

      # @!scope class
      # @!attribute [r] whitelist
      # Returns the list of allowed parameters
      #
      # @return [Array<Symbol>]

      # @!attribute [r] params
      # Service object parameters
      #
      # @return [Hash]
      attr_reader :params

      # Service object initializer
      #
      # @example Normalizing options
      #   class AddFoo
      #     include ServiceObjects::Helpers::Parameters
      #
      #     @whitelist = [:foo]
      #   end
      #
      #   service = AddFoo.new("foo" => { "bar" => "baz" })
      #   service.params # => { foo: { bar: "baz" } }
      #
      # @example Whitelisting options
      #   class AddFoo
      #     include ServiceObjects::Helpers::Parameters
      #
      #     @whitelist = [:foo]
      #   end
      #
      #   service = AddFoo.new(foo: "bar", bar: "baz")
      #   service.params # => { foo: "bar" }
      #
      # @param [Hash] options
      #
      # @return [undefined]
      def initialize(options = {})
        @params = Utils::NormalHash.from(options).slice(*__whitelist__)
      end

      private

      def self.included(klass)
        klass
          .singleton_class
          .send(:define_method, :whitelist) { @whitelist ||= [] }
        super
      end

      def __whitelist__
        @whitelist ||= self.class.send :whitelist
      end

    end # module Parameters

  end # module Helpers

end # module ServiceObjects

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
service_objects-0.1.0 lib/service_objects/helpers/parameters.rb
service_objects-0.0.2 lib/service_objects/helpers/parameters.rb
service_objects-0.0.1 lib/service_objects/helpers/parameters.rb