public
Description: A Ruby web application framework
Homepage: http://www.mackframework.com
Clone URL: git://github.com/markbates/mack.git
Search Repo:
Click here to lend your support to: mack and make a donation at www.pledgie.com !
markbates (author)
Tue May 06 15:23:50 -0700 2008
commit  649a6b539f1a8dd4922580907999522aa453c831
tree    9eb5e2562c4c2f730db7e67ee1c555204dc42f8a
parent  92f7f0b4e78f3e29a11644a0f45bceb633465b7d
mack / lib / rendering / classes / url.rb
100644 59 lines (56 sloc) 1.873 kb
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
require 'net/http'
require File.join(File.dirname(__FILE__), "..", 'base')
module Mack
  module Rendering
    # Used when someone calls render(:url => "http://www.mackframework.com")
    class Url < Base
      
      def render
        options = {:method => :get, :domain => app_config.mack.site_domain, :raise_exception => false}.merge(self.options)
        case options[:method]
        when :get
          do_render_remote_url(options) do |uri, options|
            unless options[:parameters].empty?
              uri = uri.to_s
              uri << "?"
              options[:parameters].each_pair do |k,v|
                uri << URI.encode(k.to_s)
                uri << "="
                uri << URI.encode(v.to_s)
                uri << "&"
              end
              uri.gsub!(/&$/, "")
              uri = URI.parse(uri)
            end
            Net::HTTP.get_response(uri)
          end
        when :post
          do_render_remote_url(options) do |uri, options|
            Net::HTTP.post_form(uri, options[:parameters] || {})
          end
        else
          raise Mack::Errors::UnsupportRenderUrlMethodType.new(options[:method])
        end
      end
      
      private
      def do_render_remote_url(options)
        Timeout::timeout(app_config.mack.render_url_timeout || 5) do
          url = options[:url]
          unless url.match(/^[a-zA-Z]+:\/\//)
            url = File.join(options[:domain], options[:url])
          end
          uri = URI.parse(url)
          response = yield uri, options
          if response.code == "200"
            return response.body
          else
            if options[:raise_exception]
              raise Mack::Errors::UnsuccessfulRenderUrl.new(uri, response)
            else
              return ""
            end
          end
        end
      end
      
    end # Url
  end # Rendering
end # Mack