Last active
December 16, 2015 10:58
-
-
Save okitan/5423791 to your computer and use it in GitHub Desktop.
朝の頭の体操
This file contains 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
# -*- coding: utf-8 -*- | |
class Shell < BasicObject | |
def initialize(name, *args, &block) | |
_push(name, *args) | |
end | |
attr_accessor :_result | |
attr_writer :_queue | |
def to_s | |
_queue.unshift(command: :echo, args: _result) if _result | |
command = _queue.map do |c| | |
[ c[:command], *c[:args] ].compact.map(&:to_s).join(" ") | |
end.join(" | ") | |
_queue = [] | |
# ここがどうしても無理 | |
command | |
#_result = `#{command}` | |
end | |
alias inspect to_s | |
def method_missing(name, *args, &block) | |
_push(name, *args) | |
self | |
end | |
protected | |
def _push(name, *args, &block) | |
_queue.push(command: name, args: args) | |
end | |
def _queue | |
@_queue ||= [] | |
end | |
end | |
module Shellable | |
def method_missing(name, *args, &block) | |
Shell.new(name, *args) | |
end | |
end | |
# usage 1 | |
p Shell.new(:cat, "/etc/hosts").grep("localhost") | |
# usage 2 | |
Class.new do | |
extend Shellable | |
p cat("/etc/hosts").grep("localhost") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment