Sha256: 9be608f0e6b7f8c07157575219e9cb0b580a16bf90cdd322fce36036497d7f08

Contents?: true

Size: 1.12 KB

Versions: 1

Compression:

Stored size: 1.12 KB

Contents

# frozen_string_literal: true

module ActionLink
  # A component that every other component inherits from in this gem.
  # It adds convenience methods for initialization of a component.
  class ApplicationComponent < ViewComponent::Base
    extend Dry::Initializer

    # By default, Dry::Initializer doesn't complain about invalid arguments.
    # We want it to raise an error.
    def initialize(...)
      __check_for_unknown_options(...)
      super
    end

    private

    def __check_for_unknown_options(*args, **kwargs)
      return if __defined_options.empty?

      # Checking params
      opts = args.drop(__defined_params.length).first || kwargs
      raise ArgumentError, "Unexpected argument #{opts}" unless opts.is_a? Hash

      # Checking options
      unknown_options = opts.keys - __defined_options
      message = "Key(s) #{unknown_options} not found in #{__defined_options}"
      raise KeyError, message if unknown_options.any?
    end

    def __defined_options
      self.class.dry_initializer.options.map(&:source)
    end

    def __defined_params
      self.class.dry_initializer.params.map(&:source)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
action_link-0.1.1 app/components/action_link/application_component.rb