Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improvement: better ruby from_* support in well_known_types.rb #8254

Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
deannagarcia marked this conversation as resolved.
Show resolved Hide resolved

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