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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
|
# -*- encoding : utf-8 -*-
# The MIT License (MIT)
#
# Copyright (c) 2011-2014 Hannes Georg
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
module URITemplate
# An awesome little helper which helps iterating over a string.
# Initialize with a regexp and pass a string to :each.
# It will yield a string or a MatchData
class RegexpEnumerator
include Enumerable
def initialize(regexp, options = {})
@regexp = regexp
@rest = options.fetch(:rest){ :yield }
end
def each(str)
raise ArgumentError, "RegexpEnumerator#each expects a String, but got #{str.inspect}" unless str.kind_of? String
return self.to_enum(:each,str) unless block_given?
rest = str
loop do
m = @regexp.match(rest)
if m.nil?
if rest.size > 0
yield rest
end
break
end
yield m.pre_match if m.pre_match.size > 0
yield m
if m[0].size == 0
# obviously matches empty string, so post_match will equal rest
# terminate or this will loop forever
if m.post_match.size > 0
yield m.post_match if @rest == :yield
raise "#{@regexp.inspect} matched an empty string. The rest is #{m.post_match.inspect}." if @rest == :raise
end
break
end
rest = m.post_match
end
return self
end
end
# This error will be raised whenever an object could not be converted to a param string.
class Unconvertable < StandardError
attr_reader :object
def initialize(object)
@object = object
super("Could not convert the given object (#{Object.instance_method(:inspect).bind(@object).call() rescue '<????>'}) to a param since it doesn't respond to :to_param or :to_s.")
end
end
# A collection of some utility methods.
# The most methods are used to parse or generate uri-parameters.
# I will use the escape_utils library if available, but runs happily without.
#
module Utils
KCODE_UTF8 = (Regexp::KCODE_UTF8 rescue 0)
# Bundles some string encoding methods.
module StringEncoding
# Methods which do actual encoding.
module Encode
# converts a string to ascii
#
# @param str [String]
# @return String
# @visibility public
def to_ascii(str)
str.encode(Encoding::ASCII)
end
# converts a string to utf8
#
# @param str [String]
# @return String
# @visibility public
def to_utf8(str)
str.encode(Encoding::UTF_8)
end
# enforces UTF8 encoding
#
# @param str [String]
# @return String
# @visibility public
def force_utf8(str)
return str if str.encoding == Encoding::UTF_8
str = str.dup if str.frozen?
return str.force_encoding(Encoding::UTF_8)
end
end
# Fallback methods to be used in pre 1.9 rubies.
module Fallback
def to_ascii(str)
str
end
def to_utf8(str)
str
end
def force_utf8(str)
str
end
end
# :nocov:
if "".respond_to?(:encode)
include Encode
else
include Fallback
end
# :nocov:
private :force_utf8
end
module Escaping
# A pure escaping module, which implements escaping methods in pure ruby.
# The performance is acceptable, but could be better with escape_utils.
module Pure
# @private
URL_ESCAPED = /([^A-Za-z0-9\-\._])/.freeze
# @private
URI_ESCAPED = /([^A-Za-z0-9!$&'()*+,.\/:;=?@\[\]_~])/.freeze
# @private
PCT = /%([0-9a-fA-F]{2})/.freeze
def escape_url(s)
to_utf8(s.to_s).gsub(URL_ESCAPED){
'%'+$1.unpack('H2'*$1.bytesize).join('%').upcase
}
end
def escape_uri(s)
to_utf8(s.to_s).gsub(URI_ESCAPED){
'%'+$1.unpack('H2'*$1.bytesize).join('%').upcase
}
end
def unescape_url(s)
force_utf8( to_ascii(s.to_s).gsub('+',' ').gsub(PCT){
$1.to_i(16).chr
} )
end
def unescape_uri(s)
force_utf8( to_ascii(s.to_s).gsub(PCT){
$1.to_i(16).chr
})
end
def using_escape_utils?
false
end
end
if defined? EscapeUtils
# A escaping module, which is backed by escape_utils.
# The performance is good, espacially for strings with many escaped characters.
module EscapeUtils
include ::EscapeUtils
def using_escape_utils?
true
end
def escape_url(s)
super(to_utf8(s.to_s)).gsub('+','%20')
end
def escape_uri(s)
super(to_utf8(s.to_s))
end
def unescape_url(s)
force_utf8(super(to_ascii(s.to_s)))
end
def unescape_uri(s)
force_utf8(super(to_ascii(s.to_s)))
end
end
end
end
include StringEncoding
# :nocov:
if Escaping.const_defined? :EscapeUtils
include Escaping::EscapeUtils
puts "Using escape_utils." if $VERBOSE
else
include Escaping::Pure
puts "Not using escape_utils." if $VERBOSE
end
# :nocov:
# Converts an object to a param value.
# Tries to call :to_param and then :to_s on that object.
# @raise Unconvertable if the object could not be converted.
# @example
# URITemplate::Utils.object_to_param(5) #=> "5"
# o = Object.new
# def o.to_param
# "42"
# end
# URITemplate::Utils.object_to_param(o) #=> "42"
def object_to_param(object)
if object.respond_to? :to_param
object.to_param
elsif object.respond_to? :to_s
object.to_s
else
raise Unconvertable.new(object)
end
rescue NoMethodError
raise Unconvertable.new(object)
end
# @api private
# Should we use \u.... or \x.. in regexps?
def use_unicode?
eval('Regexp.compile("\u0020")') =~ " " rescue false
end
# Returns true when the given value is an array and it only consists of arrays with two items.
# This useful when using a hash is not ideal, since it doesn't allow duplicate keys.
# @example
# URITemplate::Utils.pair_array?( Object.new ) #=> false
# URITemplate::Utils.pair_array?( [] ) #=> true
# URITemplate::Utils.pair_array?( [1,2,3] ) #=> false
# URITemplate::Utils.pair_array?( [ ['a',1],['b',2],['c',3] ] ) #=> true
# URITemplate::Utils.pair_array?( [ ['a',1],['b',2],['c',3],[] ] ) #=> false
def pair_array?(a)
return false unless a.kind_of? Array
return a.all?{|p| p.kind_of? Array and p.size == 2 }
end
# Turns the given value into a hash if it is an array of pairs.
# Otherwise it returns the value.
# You can test whether a value will be converted with {#pair_array?}.
#
# @example
# URITemplate::Utils.pair_array_to_hash( 'x' ) #=> 'x'
# URITemplate::Utils.pair_array_to_hash( [ ['a',1],['b',2],['c',3] ] ) #=> {'a'=>1,'b'=>2,'c'=>3}
# URITemplate::Utils.pair_array_to_hash( [ ['a',1],['a',2],['a',3] ] ) #=> {'a'=>3}
#
# @example Carful vs. Ignorant
# URITemplate::Utils.pair_array_to_hash( [ ['a',1],'foo','bar'], false ) #UNDEFINED!
# URITemplate::Utils.pair_array_to_hash( [ ['a',1],'foo','bar'], true ) #=> [ ['a',1], 'foo', 'bar']
#
# @param x the value to convert
# @param careful [true,false] wheter to check every array item. Use this when you expect array with subarrays which are not pairs. Setting this to false however improves runtime by ~30% even with comparetivly short arrays.
def pair_array_to_hash(x, careful = false )
if careful ? pair_array?(x) : (x.kind_of?(Array) and ( x.empty? or x.first.kind_of?(Array) ) )
return Hash[ x ]
else
return x
end
end
extend self
# @api privat
def pair_array_to_hash2(x)
c = {}
result = []
x.each do | (k,v) |
e = c[k]
if !e
result << c[k] = [k,v]
else
e[1] = [e[1]] unless e[1].kind_of? Array
e[1] << v
end
end
return result
end
# @api private
def compact_regexp(rx)
rx.split("\n").map(&:strip).join
end
end
end
|