module Skywalker::Acceptable

Public Class Methods

included(klass) click to toggle source

Creates an `_args` accessor on inclusion.

@since 2.0.0

# File lib/skywalker/acceptable.rb, line 9
def self.included(klass)
  klass.send(:attr_accessor, :_args)
end
new(**args) { |self| ... } click to toggle source

Instantiates an object, setting all kwargs as accessors, and yields self to any block given.

@since 2.0.0

# File lib/skywalker/acceptable.rb, line 20
def initialize(**args)
  self._args = args
  self._args.freeze

  validate_arguments!
  parse_arguments

  yield self if block_given?
end

Private Instance Methods

parse_arguments() click to toggle source

Creates an attr_accessor for each passed kwarg and assigns the argument.

@since 2.0.0

# File lib/skywalker/acceptable.rb, line 60
        def parse_arguments
  _args.each_pair do |reader_method, value|
    writer_method = "#{reader_method}="

    singleton_class.class_eval do
      send(:attr_reader, reader_method) unless respond_to?(reader_method)
      send(:attr_writer, reader_method) unless respond_to?(writer_method)
    end

    self.send(writer_method, value)
  end
end
required_args() click to toggle source

Specifies required arguments to the object. Should be an array of objects that are coercible to keyword names via `to_s`.

@since 2.0.0

# File lib/skywalker/acceptable.rb, line 50
        def required_args
  []
end
validate_arguments!() click to toggle source

Ensures required keys are present.

@since 2.0.0

# File lib/skywalker/acceptable.rb, line 36
        def validate_arguments!
  missing_args = required_args.map(&:to_s) - _args.keys.map(&:to_s)

  raise ArgumentError, "#{missing_args.join(", ")} required but not given" \
    if missing_args.any?
end