PageRenderTime 856ms CodeModel.GetById 744ms app.highlight 8ms RepoModel.GetById 103ms app.codeStats 0ms

/examples/custom_parsers.rb

http://github.com/jnunemaker/httparty
Ruby | 68 lines | 49 code | 14 blank | 5 comment | 0 complexity | d1bb40481da62bf36f68067948a7714b MD5 | raw file
 1dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
 2require File.join(dir, 'httparty')
 3require 'pp'
 4
 5class ParseAtom
 6  include HTTParty
 7
 8  # Support Atom along with the default parsers: xml, json, etc.
 9  class Parser::Atom < HTTParty::Parser
10    SupportedFormats.merge!({"application/atom+xml" => :atom})
11
12    protected
13
14    # perform atom parsing on body
15    def atom
16      body.to_atom
17    end
18  end
19
20  parser Parser::Atom
21end
22
23class OnlyParseAtom
24  include HTTParty
25
26  # Only support Atom
27  class Parser::OnlyAtom < HTTParty::Parser
28    SupportedFormats = { "application/atom+xml" => :atom }
29
30    protected
31
32    # perform atom parsing on body
33    def atom
34      body.to_atom
35    end
36  end
37
38  parser Parser::OnlyAtom
39end
40
41class SkipParsing
42  include HTTParty
43
44  # Parse the response body however you like
45  class Parser::Simple < HTTParty::Parser
46    def parse
47      body
48    end
49  end
50
51  parser Parser::Simple
52end
53
54class AdHocParsing
55  include HTTParty
56  parser(
57    proc do |body, format|
58      case format
59      when :json
60        body.to_json
61      when :xml
62        body.to_xml
63      else
64        body
65      end
66    end
67  )
68end