summaryrefslogtreecommitdiff
path: root/contrib/smsweb/smswsc/utils.rb
blob: fa07efd6edf54e2782c7707fa2cca866fae71f77 (plain)
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
require 'cgi'

class Time
  # try rfc3339
  # try sql
  # try rfc822
  def self.rfcdate(str)
    if str =~ /\A(\d{4})-(\d{2})-(\d{2})[T ](\d{2})\:(\d{2})\:(\d{2})/
      return Time.utc($1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i).localtime
    elsif str =~ /\A\w{3}, (\d{1,2}) (\w{3}) (\d{4}) (\d{2})\:(\d{2})\:(\d{2})/
      return Time.utc($3.to_i, $2, $1.to_i, $4.to_i, $5.to_i, $6.to_i).localtime
    else
      return nil
    end
  end
end

class Array
  def urlpath
    args, atoms = self.flatten.partition { |a| a.is_a?(Hash) }
    args = args.flatten.inject { |s, v| s.merge!(v) }

    front = atoms.join('/').squeeze('/')

    if args
      rear = args.inject('?') { |s, (k, v)|
        s << CGI::escape(k.to_s) + "=" + CGI::escape(v.to_s) + ";"
      } [0 .. -2]

      front + rear
    else
      front
    end
  end
end

module SMSWSC
  module Utils

    # Assemble a reference from arguments.
    #
    # ref("/path", "to", "it", {:q => "test"}) => "/path/to/it?q=test"

    def ref(*atoms)
      args, atoms = atoms.flatten.partition{|a| a.is_a?(Hash) }
      args = args.flatten.inject { |s, v| s.merge!(v) }
 
      front = atoms.join('/').squeeze('/')
 
      if args
        rear = args.inject('?') { |s, (k, v)|
          s << CGI::escape(k.to_s) + "=" + CGI::escape(v.to_s) + ";"
        } [0 .. -2]

        front + rear
      else
        front
      end
    end
    module_function :ref

  end
end