Sha256: 20d4f6a1fdcb81468de10de2b09745fdfad370eb9e9294c71b7c75b34ae38b2d

Contents?: true

Size: 1.04 KB

Versions: 20

Compression:

Stored size: 1.04 KB

Contents

# frozen_string_literal: true

# Problem:
#
# > fn = proc { |first| puts first  }
# > fn.call(:first, :second, :third)
# first
#
# :second and :third was ignored. It's ok.
#
# > fn = proc { puts "test"  }
# > fn.call(first: :first, second: :second, third: :third)
# test
#
# And it's ok.
#
# > fn = proc { |&block| block.call }
# > fn.call(first: :first, second: :second, third: :third) { puts "test" }
# test
#
# And this is ok too.
#
# > fn = proc { |first:| puts first  }
# > fn.call(first: :first, second: :second, third: :third)
# ArgumentError (unknown keywords: :second, :third)
#
# ¯\_(ツ)_/¯
#
# ❤ Ruby ❤
#
# Next code solve this problem for procs without word arguments,
# only keywords and block.

module TableSync::Utils
  module_function

  def proc_keywords_resolver(&proc_for_wrap)
    available_keywords = proc_for_wrap.parameters
      .select { |type, _name| type == :keyreq }
      .map { |_type, name| name }

    proc do |keywords = {}, &block|
      proc_for_wrap.call(**keywords.slice(*available_keywords), &block)
    end
  end
end

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
table_sync-6.5.1 lib/table_sync/utils/proc_keywords_resolver.rb
table_sync-6.5.0 lib/table_sync/utils/proc_keywords_resolver.rb
table_sync-6.4.2 lib/table_sync/utils/proc_keywords_resolver.rb
table_sync-6.4.1 lib/table_sync/utils/proc_keywords_resolver.rb
table_sync-6.4.0 lib/table_sync/utils/proc_keywords_resolver.rb
table_sync-6.3.0 lib/table_sync/utils/proc_keywords_resolver.rb
table_sync-6.1.0 lib/table_sync/utils/proc_keywords_resolver.rb
table_sync-6.0.4 lib/table_sync/utils/proc_keywords_resolver.rb
table_sync-6.0.3 lib/table_sync/utils/proc_keywords_resolver.rb
table_sync-6.0.2 lib/table_sync/utils/proc_keywords_resolver.rb
table_sync-6.0 lib/table_sync/utils/proc_keywords_resolver.rb
table_sync-5.1.0 lib/table_sync/utils/proc_keywords_resolver.rb
table_sync-5.0.0 lib/table_sync/utils/proc_keywords_resolver.rb
table_sync-4.2.2 lib/table_sync/utils/proc_keywords_resolver.rb
table_sync-4.2.1 lib/table_sync/utils/proc_keywords_resolver.rb
table_sync-4.2.0 lib/table_sync/utils/proc_keywords_resolver.rb
table_sync-4.1.3 lib/table_sync/utils/proc_keywords_resolver.rb
table_sync-4.1.1 lib/table_sync/utils/proc_keywords_resolver.rb
table_sync-4.1.0 lib/table_sync/utils/proc_keywords_resolver.rb
table_sync-4.0.0 lib/table_sync/utils/proc_keywords_resolver.rb