/
binary.rb
62 lines (53 loc) · 1.26 KB
/
binary.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
# frozen_string_literal: true
module ActiveModel
module Type
# = Active Model \Binary \Type
#
# Attribute type for representation of binary data. This type is registered
# under the +:binary+ key.
#
# Non-string values are coerced to strings using their +to_s+ method.
class Binary < Value
def type
:binary
end
def binary?
true
end
def cast(value)
if value.is_a?(Data)
value.to_s
else
value = super
value = value.b if ::String === value && value.encoding != Encoding::BINARY
value
end
end
def serialize(value)
return if value.nil?
Data.new(super)
end
def changed_in_place?(raw_old_value, value)
old_value = deserialize(raw_old_value)
old_value != value
end
class Data # :nodoc:
def initialize(value)
value = value.to_s
value = value.b unless value.encoding == Encoding::BINARY
@value = value
end
def to_s
@value
end
alias_method :to_str, :to_s
def hex
@value.unpack1("H*")
end
def ==(other)
other == to_s || super
end
end
end
end
end