Created
May 7, 2019 19:20
-
-
Save pkoch/f275222bce147d9f781c26bb49c05f4c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
diff --git a/app/lib/p.rb b/app/lib/p.rb | |
new file mode 100644 | |
index 0000000..96e939c | |
--- /dev/null | |
+++ b/app/lib/p.rb | |
@@ -0,0 +1,67 @@ | |
+module P | |
+ class PartialApplier < BasicObject | |
+ attr_reader :target | |
+ | |
+ def initialize(target) | |
+ @target = target | |
+ end | |
+ | |
+ def respond_to_missing?(method_name, include_private = false) | |
+ true | |
+ end | |
+ | |
+ def method_missing(name, *args, &blk) # rubocop:disable Style/MethodMissingSuper | |
+ i = args.index(::P) || 0 | |
+ make_args = ->(o) { | |
+ args.dup.tap { |ary| ary.delete_at(i) }.insert(i, o) | |
+ } | |
+ ->(o) do | |
+ target.method(name).call(*make_args[o], &blk) | |
+ end | |
+ end | |
+ end | |
+ | |
+ module ModulesAndClasses | |
+ def partial_applier | |
+ PartialApplier.new(self) | |
+ end | |
+ | |
+ alias P partial_applier | |
+ end | |
+ | |
+ module Array | |
+ def reduce_compose | |
+ map(&:to_proc).reduce(&:>>) | |
+ end | |
+ | |
+ alias P reduce_compose | |
+ end | |
+ | |
+ module NiceShorts | |
+ def respond_to_missing?(method_name, include_private = false) | |
+ true | |
+ end | |
+ | |
+ def method_missing(name, *args, &blk) # rubocop:disable Style/MethodMissingSuper | |
+ ->(o) { o.method(name)[*args, &blk] } | |
+ end | |
+ end | |
+ | |
+ extend NiceShorts | |
+ | |
+ unless ::Array.method_defined? :P | |
+ ::Array.prepend ::P::Array | |
+ end | |
+ | |
+ unless Module.method_defined? :P | |
+ Module.include ModulesAndClasses | |
+ end | |
+ | |
+ unless Class.method_defined? :P | |
+ Class.include ModulesAndClasses | |
+ end | |
+ | |
+ unless Object.method_defined? :P | |
+ Object.include ModulesAndClasses | |
+ end | |
+end | |
diff --git a/test/lib/p_test.rb b/test/lib/p_test.rb | |
new file mode 100644 | |
index 0000000..b07b0e9 | |
--- /dev/null | |
+++ b/test/lib/p_test.rb | |
@@ -0,0 +1,27 @@ | |
+# works? | |
+require "test_helper" | |
+ | |
+P.load | |
+ | |
+class PTest < ActiveSupport::TestCase | |
+ def example(left, right) | |
+ [left, right].join(" ") | |
+ end | |
+ | |
+ test "api" do | |
+ io = StringIO.new | |
+ | |
+ __FILE__.then(&[ | |
+ File.P.open("rb"), | |
+ :read, | |
+ P.split("\n"), | |
+ P.map(&:upcase), | |
+ :first, | |
+ P[/([A-Z]+)/, 1], | |
+ self.P.example("it", P), | |
+ io.P.write, | |
+ ].P) | |
+ | |
+ assert_equal "it WORKS", io.string | |
+ end | |
+end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment