Add RDF.Writer and corresponding write functions on RDF.Serialization

This commit is contained in:
Marcel Otto 2017-06-16 18:32:41 +02:00
parent 1fdb64c646
commit f3168e1682
2 changed files with 80 additions and 0 deletions

View file

@ -80,6 +80,15 @@ defmodule RDF.Serialization do
def read_file!(file, opts \\ []),
do: RDF.Reader.read_file!(decoder(), file, opts)
def write_string(data, opts \\ []),
do: RDF.Writer.write_string(encoder(), data, opts)
def write_string!(data, opts \\ []),
do: RDF.Writer.write_string!(encoder(), data, opts)
def write_file(data, path, opts \\ []),
do: RDF.Writer.write_file(encoder(), data, path, opts)
def write_file!(data, path, opts \\ []),
do: RDF.Writer.write_file!(encoder(), data, path, opts)
@before_compile unquote(__MODULE__)
end
end

71
lib/rdf/writer.ex Normal file
View file

@ -0,0 +1,71 @@
defmodule RDF.Writer do
@moduledoc """
General serialization-independent functions for writing the statements of a `RDF.Graph` or `RDF.Dataset` to a file or string.
You probably won't use these functions directly, but instead use the automatically
generated functions with same name on a `RDF.Serialization`, which implicitly
use the proper `RDF.Serialization.Encoder` module.
"""
@doc """
Encodes and writes a graph or dataset to a string.
It returns an `{:ok, string}` tuple, with `string` being the serialized graph or
dataset, or `{:error, reason}` if an error occurs.
"""
def write_string(encoder, data, opts \\ []) do
encoder.encode(data, opts)
end
@doc """
Encodes and writes a graph or dataset to a string.
As opposed to `write_string`, it raises an exception if an error occurs.
"""
def write_string!(encoder, data, opts \\ []) do
encoder.encode!(data, opts)
end
@doc """
Encodes and writes a graph or dataset to a file.
General available serialization-independent options:
- `:force` - If not set to `true`, an error is raised when the given file
already exists (default: `false`)
- `:file_mode` - A list with the Elixir `File.open` modes to be used fior writing
(default: `[:utf8, :write]`)
It returns `:ok` if successfull or `{:error, reason}` if an error occurs.
"""
def write_file(encoder, data, path, opts \\ []) do
with {:ok, encoded_string} <- write_string(encoder, data, opts) do
File.write(path, encoded_string, file_mode(encoder, opts))
end
end
@doc """
Encodes and writes a graph or dataset to a file.
See `write_file` for a list of available options.
As opposed to `write_file`, it raises an exception if an error occurs.
"""
def write_file!(encoder, data, path, opts \\ []) do
with encoded_string = write_string!(encoder, data, opts) do
File.write!(path, encoded_string, file_mode(encoder, opts))
end
end
defp file_mode(_encoder, opts) do
with file_mode = Keyword.get(opts, :file_mode, ~w[utf8 write exclusive]a) do
if Keyword.get(opts, :force) do
List.delete(file_mode, :exclusive)
else
file_mode
end
end
end
end