Added v 0.3.1 snapshot.
[twitter4r-core.git] / lib / twitter / ext / stdlib.rb
blobc6fd99e6e4da36ef78c730d0ce5b9130d150ea3a
1 # Contains Ruby standard library extensions specific to <tt>Twitter4R</tt> library.
3 # Extension to Hash to create URL encoded string from key-values
4 class Hash
5   # Returns string formatted for HTTP URL encoded name-value pairs.
6   # For example,
7   #  {:id => 'thomas_hardy'}.to_http_str 
8   #  # => "id=thomas_hardy"
9   #  {:id => 23423, :since => Time.now}.to_http_str
10   #  # => "since=Thu,%2021%20Jun%202007%2012:10:05%20-0500&id=23423"
11   def to_http_str
12     result = ''
13     return result if self.empty?
14     self.each do |key, val|
15       result << "#{key}=#{CGI.escape(val.to_s)}&"
16     end
17     result.chop # remove the last '&' character, since it can be discarded
18   end
19 end
21 # Extension to Time that outputs RFC2822 compliant string on #to_s
22 class Time
23   alias :old_to_s :to_s
24   
25   # Returns RFC2822 compliant string for <tt>Time</tt> object.
26   # For example,
27   #  # Tony Blair's last day in office (hopefully)
28   #  best_day_ever = Time.local(2007, 6, 27)
29   #  best_day_ever.to_s # => "Wed, 27 Jun 2007 00:00:00 +0100"
30   # You can also pass in an option <tt>format</tt> argument that 
31   # corresponds to acceptable values according to ActiveSupport's 
32   # +Time#to_formatted_s+ method.
33   def to_s(format = nil)
34     format ? self.to_formatted_s(format) : self.rfc2822
35   end
36 end
38 # Extension to Kernel to add #gem_present? without any exceptions raised
39 module Kernel
41   # Returns whether or not a gem exists without raising a Gem::LoadError exception
42   def gem_present?(gem_name, version = nil)
43     present = false
44     begin
45       present = !!(version ? gem(gem_name, version) : gem(gem_name))
46     rescue Gem::LoadError => le
47       present = false
48       warn("Gem load error: Couldn't load #{gem_name} #{version ? "with version requirement #{version}: #{le.to_s}": ""}")
49     end
50     present
51   end
52 end