Improvement: better ruby from_* support in well_known_types.rb

* Added capability to support from_* requests properly by adding class methods and returning self for instance methods
    * `Timestamp.from_time`
    * `Value.from_ruby`
pull/8254/head
Joel Courtney 4 years ago
parent aa13fde017
commit ef70acbc03
  1. 36
      ruby/lib/google/protobuf/well_known_types.rb
  2. 14
      ruby/tests/well_known_types_test.rb

@ -82,9 +82,14 @@ module Google
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
@ -131,6 +136,34 @@ module Google
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
@ -155,6 +188,8 @@ module Google
else
raise UnexpectedStructType
end
self
end
end
@ -225,6 +260,5 @@ module Google
ret
end
end
end
end

@ -15,16 +15,26 @@ class TestWellKnownTypes < Test::Unit::TestCase
# 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

Loading…
Cancel
Save