Skip to content

Commit

Permalink
Improvement: better ruby from_* support in well_known_types.rb
Browse files Browse the repository at this point in the history
* Added capability to support from_* requests properly by adding class methods and returning self for instance methods
    * `Timestamp.from_time`
    * `Value.from_ruby`
  • Loading branch information
jufemaiz committed Feb 3, 2021
1 parent aa13fde commit ef70acb
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 3 deletions.
36 changes: 35 additions & 1 deletion ruby/lib/google/protobuf/well_known_types.rb
Expand Up @@ -82,9 +82,14 @@ def to_time
end
end

def self.from_time(time)
Timestamp.new(seconds: time.to_i, nanos: time.nsec)
end

def from_time(time)
self.seconds = time.to_i
self.nanos = time.nsec
self
end

def to_i
Expand Down Expand Up @@ -131,6 +136,34 @@ def to_ruby(recursive = false)
raise UnexpectedStructType
end
end

def self.from_ruby(value)
ret = Value.new
case value
when NilClass
ret.null_value = 0
when Numeric
ret.number_value = value
when String
ret.string_value = value
when TrueClass
ret.bool_value = true
when FalseClass
ret.bool_value = false
when Struct
ret.struct_value = value
when Hash
ret.struct_value = Struct.from_hash(value)
when ListValue
ret.list_value = value
when Array
ret.list_value = ListValue.from_a(value)
else
raise UnexpectedStructType
end

ret
end

def from_ruby(value)
case value
Expand All @@ -155,6 +188,8 @@ def from_ruby(value)
else
raise UnexpectedStructType
end

self
end
end

Expand Down Expand Up @@ -225,6 +260,5 @@ def self.from_a(arr)
ret
end
end

end
end
14 changes: 12 additions & 2 deletions ruby/tests/well_known_types_test.rb
Expand Up @@ -15,16 +15,26 @@ def test_timestamp

# millisecond accuracy
time = Time.at(123456, 654321)
ts.from_time(time)
resp = ts.from_time(time)
assert_equal 123456, ts.seconds
assert_equal 654321000, ts.nanos
assert_equal time, ts.to_time
assert_equal resp, ts

# nanosecond accuracy
time = Time.at(123456, Rational(654321321, 1000))
ts.from_time(time)
resp = ts.from_time(time)
assert_equal 123456, ts.seconds
assert_equal 654321321, ts.nanos
assert_equal time, ts.to_time
assert_equal resp, ts

# Class based initialisation using from_time
time = Time.at(123456, Rational(654321321, 1000))
ts = Google::Protobuf::Timestamp.from_time(time)
assert_equal 123456, ts.seconds
assert_equal 654321000, ts.nanos
assert_equal time, ts.to_time
end

def test_duration
Expand Down

0 comments on commit ef70acb

Please sign in to comment.