public
Last active — forked from defunkt/url_dsl.rb

  • Download Gist
url_dsl.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
require 'open-uri'
 
# url dsl -- the ultimate url dsl!
#
# You just can't beat this:
#
# $ irb -r url_dsl
# >> include URLDSL
# => Object
# >> http://github.com/defunkt.json
# => #<URLDSL::Request http://github.com/defunkt.json/>
# >> puts http://github.com/defunkt.json
# [{"repository":{"url":"http://github.com/defunkt/repl",
# ... etc ...
# => nil
#
# Or this:
#
# >> require 'json'
# => true
# >> url = http://twitter.com/statuses/show/6592721580.json
# => #<URLDSL::Request http://twitter.com/statuses/show/6592721580.json/>
# >> JSON.parse(url.to_s)['text']
# => "He nose the truth."
#
 
 
# Helper for using URLDSL in a Ruby file:
#
# URLDSL do
# puts http://twitter.com/brosner/status/6592721580.json
# end
def URLDSL(&block)
$urldsl_req = URLDSL::Request.new
$urldsl_req.instance_eval(&block)
ensure
$urldsl_req = nil
end
 
module URLDSL
# This included hack is for `irb':
#
# >> include URLDSL
# => Object
# >> http://github.com/api/v2/yaml/repos/show/schacon/grit
# => <yaml>
 
def self.included(base)
$urldsl_req = URLDSL::Request.new
 
base.class_eval do
def method_missing(*args, &block)
$urldsl_req.send(*args, &block)
end
end
end
 
module SymbolHack
def /(other = nil)
return super unless other.is_a? Request
other << "/"
other
end
end
Symbol.send :include, SymbolHack
 
module NumberHack
def method_missing(name, *args)
$urldsl_req << self
$urldsl_req << name
self
end
end
Integer.send :include, NumberHack
 
class Request
attr_accessor :protocol, :calls
def initialize
@calls = []
@protocol = :http
end
 
def <<(method)
@calls << method
end
 
def url
build_url
ensure
@calls = []
end
 
def build_url
protocol.to_s + '://' +
@calls.join('.').
gsub('./', '/').
gsub('/.', '/').
squeeze('/')
end
 
def to_s
@to_s ||= open(url).read
end
 
def inspect
"#<URLDSL::Request %s>" % build_url
end
 
def method_missing(name, *args)
@to_s = nil
 
if name.to_s =~ /https?/
@protocol = name
else
self << name
end
 
args.each do |arg|
self << arg unless arg.is_a?(Request) || @calls.include?(arg)
end
 
self
end
end
end
 
 
URLDSL do
 
puts http://twitter.com/statuses/show/6592721580.json
 
require 'yaml'
url = http://github.com/api/v2/yaml/repos/show/schacon/grit
puts YAML.load(url.to_s)['repository'][:name]
 
end if $0 == __FILE__

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.