Skip to content

Instantly share code, notes, and snippets.

@okitan
Last active December 16, 2015 10:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save okitan/5423791 to your computer and use it in GitHub Desktop.
Save okitan/5423791 to your computer and use it in GitHub Desktop.
朝の頭の体操
# -*- 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