diff --git a/ruby/lib/google/protobuf/well_known_types.rb b/ruby/lib/google/protobuf/well_known_types.rb index 37f8d5b675cd..942782026c09 100755 --- a/ruby/lib/google/protobuf/well_known_types.rb +++ b/ruby/lib/google/protobuf/well_known_types.rb @@ -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 @@ -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 @@ -155,6 +188,8 @@ def from_ruby(value) else raise UnexpectedStructType end + + self end end @@ -225,6 +260,5 @@ def self.from_a(arr) ret end end - end end diff --git a/ruby/tests/well_known_types_test.rb b/ruby/tests/well_known_types_test.rb index 3eafe095ad0f..9949795250cd 100755 --- a/ruby/tests/well_known_types_test.rb +++ b/ruby/tests/well_known_types_test.rb @@ -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