Created
July 15, 2019 18:44
-
-
Save pkoch/9a50b31f91f404acc12236c35a72f47e to your computer and use it in GitHub Desktop.
p.rb
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
commit 1b7d0c1b7ea0c44ec27df33d72306fd9655fa2bb | |
Author: Paulo Köch <[email protected]> | |
Date: Mon May 13 10:23:18 2019 +0200 | |
Introduce P | |
diff --git a/app/lib/p.rb b/app/lib/p.rb | |
new file mode 100644 | |
index 0000000..4f31a50 | |
--- /dev/null | |
+++ b/app/lib/p.rb | |
@@ -0,0 +1,54 @@ | |
+module P | |
+ class PartialApplier < BasicObject | |
+ 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 | |
+ args.unshift(::P) unless args.include? ::P | |
+ i = args.index(::P) | |
+ make_args = ->(o) { | |
+ args.dup.tap { |a| a.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 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 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..7df2fe7 | |
--- /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") | |
+ .>> P.read | |
+ .>> P.split("\n") | |
+ .>> P.map(&:upcase) | |
+ .>> P.first | |
+ .>> P[/([A-Z]+)/, 1] | |
+ .>> self.P.example("it", P) | |
+ .>> io.P.write | |
+ )) | |
+ | |
+ 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