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

Update README.md #20

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ Example:

```crystal
require "protobuf"
require "tempfile"

enum Foo
FOO
Expand All @@ -56,15 +57,23 @@ struct MyMessage
# write your methods like you normally would here, if you like.
end

proto_io = File.read("path/to/encoded/protobuf") # get your IO in some way
# MyMessage is just a normal struct - let's create one
msg = MyMessage.new prop_name: 42, prop2: Foo::FOO, optional_prop_name: "Bar"
puts "Before serialization: #{msg}"

msg = MyMessage.from_protobuf(proto_io) # returns a an instance of MyMessage
# from a valid protobuf encoded message
io_memory = msg.to_protobuf # io_memory is an IO::Memory of the encoded message

msg.to_protobuf # return a IO::Memory filled with the encoded message
# Or write the encoded message into any IO object - such as network, or a file
tmpfile = Tempfile.open("my_message") do |output_file|
msg.to_protobuf output_file # In this case we use a temporary file
end

# Now let's decode the message...
input_file = File.open(tmpfile.path) # open an IO object (the file we just wrote)
decoded_msg = MyMessage.from_protobuf(input_file) # return an instance of MyMessage

some_io = IO::Memory.new
msg.to_protobuf(some_io) # fills up the provided IO with the encoded message
puts "After serialization: #{decoded_msg}"
tmpfile.delete # clean up the temporary file
```

#### Field types
Expand Down