-
Notifications
You must be signed in to change notification settings - Fork 182
/
text_encoder.rb
69 lines (60 loc) · 1.81 KB
/
text_encoder.rb
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
# -*- ruby -*-
require 'json'
require 'ipaddr'
module PG
module TextEncoder
class Date < SimpleEncoder
STRFTIME_ISO_DATE = "%Y-%m-%d".freeze
def encode(value)
value.respond_to?(:strftime) ? value.strftime(STRFTIME_ISO_DATE) : value
end
end
class TimestampWithoutTimeZone < SimpleEncoder
STRFTIME_ISO_DATETIME_WITHOUT_TIMEZONE = "%Y-%m-%d %H:%M:%S.%N".freeze
def encode(value)
value.respond_to?(:strftime) ? value.strftime(STRFTIME_ISO_DATETIME_WITHOUT_TIMEZONE) : value
end
end
class TimestampUtc < SimpleEncoder
STRFTIME_ISO_DATETIME_WITHOUT_TIMEZONE_UTC = "%Y-%m-%d %H:%M:%S.%N".freeze
def encode(value)
value.respond_to?(:utc) ? value.utc.strftime(STRFTIME_ISO_DATETIME_WITHOUT_TIMEZONE_UTC) : value
end
end
class TimestampWithTimeZone < SimpleEncoder
STRFTIME_ISO_DATETIME_WITH_TIMEZONE = "%Y-%m-%d %H:%M:%S.%N %:z".freeze
def encode(value)
value.respond_to?(:strftime) ? value.strftime(STRFTIME_ISO_DATETIME_WITH_TIMEZONE) : value
end
end
class Numeric < SimpleEncoder
def encode(value)
value.is_a?(BigDecimal) ? value.to_s('F') : value
end
end
class JSON < SimpleEncoder
def encode(value)
::JSON.generate(value, quirks_mode: true)
end
end
class Inet < SimpleEncoder
def encode(value)
case value
when IPAddr
default_prefix = (value.family == Socket::AF_INET ? 32 : 128)
s = value.to_s
if value.respond_to?(:prefix)
prefix = value.prefix
else
range = value.to_range
prefix = default_prefix - Math.log(((range.end.to_i - range.begin.to_i) + 1), 2).to_i
end
s << "/" << prefix.to_s if prefix != default_prefix
s
else
value
end
end
end
end
end # module PG