Skip to content

Commit

Permalink
Add class method from_time to ruby well known types - Timestamp
Browse files Browse the repository at this point in the history
  • Loading branch information
mcclymont committed May 5, 2021
1 parent 2a11e89 commit 6d847ad
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
5 changes: 5 additions & 0 deletions ruby/lib/google/protobuf/well_known_types.rb
Expand Up @@ -85,6 +85,11 @@ def to_time
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
Expand Down
8 changes: 6 additions & 2 deletions ruby/tests/well_known_types_test.rb
Expand Up @@ -15,16 +15,20 @@ def test_timestamp

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

# nanosecond accuracy
time = Time.at(123456, Rational(654321321, 1000))
ts.from_time(time)
ts = Google::Protobuf::Timestamp.from_time(time)
assert_equal 654321321, 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

def test_duration
Expand Down

0 comments on commit 6d847ad

Please sign in to comment.