Module: EventedNet::HTTP::Post
- Included in:
- EventedNet::HTTP
- Defined in:
- lib/http/post.rb
Instance Method Summary collapse
- #evented_post(uri, opts) ⇒ Object
- #post(uri, opts = {}) ⇒ Object
- #synchronous_post(uri, opts) ⇒ Object
- #urlencode(str) ⇒ Object
Instance Method Details
#evented_post(uri, opts) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/http/post.rb', line 18 def evented_post(uri, opts) post_params = opts[:params] || {} post_params = post_params.collect{ |k,v| "#{urlencode(k.to_s)}=#{urlencode(v.to_s)}"}.join('&') http = EventedNet::HTTP::Connection.request( :host => uri.host, :port => uri.port, :request => uri.path, :content => post_params, :head => { 'Content-type' => opts[:content_type] || 'application/x-www-form-urlencoded' }, :method => 'POST' ) # Assign the user generated callback, as the callback for # EM::Protocols::HttpClient http.callback { |r| puts "#{r.inspect}"; opts[:callback].call(r[:status], r[:content]) } end |
#post(uri, opts = {}) ⇒ Object
4 5 6 7 8 9 |
# File 'lib/http/post.rb', line 4 def post(uri, opts = {}) unless uri.is_a?(URI) && (opts[:callback].is_a?(Proc) || opts[:callback].is_a?(Method)) && opts[:callback].arity == 2 raise ArgumentError, "uri must be a URI and opts[:callback] must be a Proc (or Method) which takes 2 args" end EM.reactor_running? ? evented_post(uri, opts) : synchronous_post(uri, opts) end |
#synchronous_post(uri, opts) ⇒ Object
12 13 14 15 16 |
# File 'lib/http/post.rb', line 12 def synchronous_post(uri, opts) post_params = opts[:params] || {} r = Net::HTTP.post_form(uri, post_params) opts[:callback].call(r.code, r.body) end |
#urlencode(str) ⇒ Object
36 37 38 |
# File 'lib/http/post.rb', line 36 def urlencode(str) str.gsub(/[^a-zA-Z0-9_\.\-]/n) {|s| sprintf('%%%02x', s[0]) } end |