| 1 |
#!/usr/bin/env ruby |
| 2 |
|
| 3 |
# jsonclient shell command. |
| 4 |
# |
| 5 |
# Usage: 1) % jsonclient post https://www.example.com/ content.json |
| 6 |
# Usage: 2) % jsonclient |
| 7 |
# |
| 8 |
# For 1) it issues a GET request to the given URI and shows the wiredump and |
| 9 |
# the parsed result. For 2) it invokes irb shell with the binding that has a |
| 10 |
# JSONClient as 'self'. You can call JSONClient instance methods like; |
| 11 |
# > post "https://www.example.com/resource", {'hello' => 'world'} |
| 12 |
require 'jsonclient' |
| 13 |
|
| 14 |
method = ARGV.shift |
| 15 |
url = ARGV.shift |
| 16 |
body = [] |
| 17 |
if ['post', 'put'].include?(method) |
| 18 |
if ARGV.size == 1 && File.exist?(ARGV[0]) |
| 19 |
body << File.read(ARGV[0]) |
| 20 |
else |
| 21 |
body << ARGF.read |
| 22 |
end |
| 23 |
end |
| 24 |
if method && url |
| 25 |
require 'pp' |
| 26 |
client = JSONClient.new |
| 27 |
client.debug_dev = STDERR if $DEBUG |
| 28 |
res = client.send(method, url, *body) |
| 29 |
STDERR.puts('RESPONSE HEADER: ') |
| 30 |
PP.pp(res.headers, STDERR) |
| 31 |
if res.ok? |
| 32 |
begin |
| 33 |
puts JSON.pretty_generate(res.content) |
| 34 |
rescue JSON::GeneratorError |
| 35 |
puts res.content |
| 36 |
end |
| 37 |
exit 0 |
| 38 |
else |
| 39 |
STDERR.puts res.content |
| 40 |
exit 1 |
| 41 |
end |
| 42 |
end |
| 43 |
|
| 44 |
require 'irb' |
| 45 |
require 'irb/completion' |
| 46 |
|
| 47 |
class Runner |
| 48 |
def initialize |
| 49 |
@httpclient = JSONClient.new |
| 50 |
end |
| 51 |
|
| 52 |
def method_missing(msg, *a, &b) |
| 53 |
debug, $DEBUG = $DEBUG, true |
| 54 |
begin |
| 55 |
@httpclient.send(msg, *a, &b) |
| 56 |
ensure |
| 57 |
$DEBUG = debug |
| 58 |
end |
| 59 |
end |
| 60 |
|
| 61 |
def run |
| 62 |
IRB.setup(nil) |
| 63 |
ws = IRB::WorkSpace.new(binding) |
| 64 |
irb = IRB::Irb.new(ws) |
| 65 |
IRB.conf[:MAIN_CONTEXT] = irb.context |
| 66 |
|
| 67 |
trap("SIGINT") do |
| 68 |
irb.signal_handle |
| 69 |
end |
| 70 |
|
| 71 |
begin |
| 72 |
catch(:IRB_EXIT) do |
| 73 |
irb.eval_input |
| 74 |
end |
| 75 |
ensure |
| 76 |
IRB.irb_at_exit |
| 77 |
end |
| 78 |
end |
| 79 |
|
| 80 |
def to_s |
| 81 |
'JSONClient' |
| 82 |
end |
| 83 |
end |
| 84 |
|
| 85 |
Runner.new.run |