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 2 commits
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
15 changes: 10 additions & 5 deletions ruby/lib/google/protobuf/well_known_types.rb
Expand Up @@ -82,16 +82,16 @@ def to_time
end
end

def self.from_time(time)
new.from_time(time)
end

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

def self.from_time(time)
new.from_time(time)
end

def to_i
self.seconds
end
Expand Down Expand Up @@ -136,6 +136,10 @@ def to_ruby(recursive = false)
raise UnexpectedStructType
end
end

def self.from_ruby(value)
Value.new.from_ruby(value)
end
deannagarcia marked this conversation as resolved.
Show resolved Hide resolved

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

self
end
end

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

end
end
18 changes: 14 additions & 4 deletions ruby/tests/well_known_types_test.rb
Expand Up @@ -15,21 +15,31 @@ def test_timestamp

# millisecond accuracy
time = Time.at(123456, 654321)
ts = Google::Protobuf::Timestamp.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 = Google::Protobuf::Timestamp.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

# Instance method returns the same value as class method
# 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

# Instance method returns the same value as class method
assert_equal Google::Protobuf::Timestamp.new.from_time(time),
Google::Protobuf::Timestamp.from_time(time)
end
end
deannagarcia marked this conversation as resolved.
Show resolved Hide resolved

def test_duration
duration = Google::Protobuf::Duration.new(seconds: 123, nanos: 456)
Expand Down