module OptStruct::InstanceMethods

Public Class Methods

new(*arguments, **options) click to toggle source
# File lib/opt_struct/instance_methods.rb, line 3
def initialize(*arguments, **options)
  with_init_callbacks do
    @options = options
    assign_arguments(arguments)
    assign_defaults
    check_required_keys
  end
end

Public Instance Methods

defaults() click to toggle source
# File lib/opt_struct/instance_methods.rb, line 16
def defaults
  self.class.defaults
end
fetch(*a, &b) click to toggle source
# File lib/opt_struct/instance_methods.rb, line 12
def fetch(*a, &b)
  options.fetch(*a, &b)
end

Private Instance Methods

assign_arguments(args) click to toggle source
# File lib/opt_struct/instance_methods.rb, line 36
def assign_arguments(args)
  self.class.expected_arguments.map.with_index do |key, i|
    options[key] = args[i] if args.length > i
  end
end
assign_defaults() click to toggle source
# File lib/opt_struct/instance_methods.rb, line 29
def assign_defaults
  defaults.each do |key, default_value|
    next if options.key?(key)
    options[key] = read_default_value(default_value)
  end
end
check_required_keys() click to toggle source
# File lib/opt_struct/instance_methods.rb, line 22
def check_required_keys
  missing = self.class.required_keys.reject { |key| options.key?(key) }
  if missing.any?
    raise ArgumentError, "missing required keywords: #{missing.inspect}"
  end
end
read_default_value(default) click to toggle source
# File lib/opt_struct/instance_methods.rb, line 42
def read_default_value(default)
  case default
  when Proc
    instance_exec(&default)
  when Symbol
    respond_to?(default) ? send(default) : default
  else
    default
  end
end
run_befores_and_afters(before, after) { || ... } click to toggle source
# File lib/opt_struct/instance_methods.rb, line 72
def run_befores_and_afters(before, after)
  before.each { |cb| run_callback(cb) }
  yield
  after.each { |cb| run_callback(cb) }
end
run_callback(callback, &to_yield) click to toggle source
# File lib/opt_struct/instance_methods.rb, line 78
def run_callback(callback, &to_yield)
  case callback
  when Symbol, String
    send(callback, &to_yield)
  when Proc
    instance_exec(to_yield, &callback)
  end
end
with_init_callbacks() { || ... } click to toggle source
# File lib/opt_struct/instance_methods.rb, line 53
def with_init_callbacks(&init_block)
  callbacks = self.class.all_callbacks
  return yield if callbacks.nil? || callbacks.empty?

  around, before, after = [:around_init, :before_init, :init].map do |type|
    callbacks.fetch(type) { [] }
  end

  if around.any?
    init = proc { run_befores_and_afters(before, after, &init_block) }
    init = around.reduce(init) do |chain, callback|
      proc { run_callback(callback, &chain) }
    end
    instance_exec(&init)
  else
    run_befores_and_afters(before, after, &init_block)
  end
end