Permalink
Browse files

Added Enumerable#to_{writer} and Mutable#from_{reader} behavior in me…

…thod_missing based on all available Readers/Writers. This addresses issue #105
  • Loading branch information...
1 parent a76efbd commit 3ff7ee9650f36ef5f86766b116c831419c8a680e @gkellogg gkellogg committed Mar 20, 2013
Showing with 50 additions and 3 deletions.
  1. +17 −0 README.md
  2. +16 −0 lib/rdf/mixin/enumerable.rb
  3. +17 −3 lib/rdf/mixin/mutable.rb
View
@@ -115,6 +115,23 @@ A specific sub-type of Writer can also be invoked directly:
graph.dump(:nquads)
+## Reader/Writer convenience methods
+{RDF::Enumerable} implements `to_{format}` for each available instance of {RDF::Reader}.
+For example, if `rdf/turtle` is loaded, this allows the following:
+
+ graph = RDF::Graph.new << [:hello, RDF::DC.title, "Hello, world!"]
+ graph.to_ttl
+
+Similarly, {RDF::Mutable} implements `from_{format}` for each available instance
+of {RDF::Writer}. For example:
+
+ graph = RDF::Graph.new
+ graph.from_ttl("[ a <http://www.w3.org/1999/02/22-rdf-syntax-ns#Resource>]")
+
+Note that no prefixes are loaded automatically, however they can be provided as arguments:
+
+ graph.from_ttl("[ a rdf:Resource]", :prefixes => {:rdf => RDF.to_uri})
+
### Querying RDF data using basic graph patterns (BGPs)
require 'rdf/ntriples'
@@ -665,5 +665,21 @@ def dump(*args)
raise RDF::WriterError, "No writer found using #{args.inspect}" unless writer
writer.dump(self, nil, options)
end
+
+ ##
+ # @overload #to_{writer}
+ # Implements #to_{writer} for each available instance of {RDF::Writer},
+ # based on the writer symbol.
+ #
+ # @return [String]
+ # @see {RDF::Writer.sym}
+ def method_missing(meth, *args)
+ writer = RDF::Writer.for(meth.to_s[3..-1].to_sym) if meth.to_s[0,3] == "to_"
+ if writer
+ writer.buffer(:standard_prefixes => true) {|w| w << self}
+ else
+ super
+ end
+ end
end # Enumerable
end # RDF
View
@@ -152,6 +152,23 @@ def clear
alias_method :clear!, :clear
+ ##
+ # @overload #from_{reader}
+ # Implements #to_{reader} for each available instance of {RDF::Reader},
+ # based on the reader symbol.
+ #
+ # Arguments are passed to Reader.new.
+ #
+ # @return [String]
+ # @see {RDF::Reader.sym}
+ def method_missing(meth, *args)
+ reader = RDF::Reader.for(meth.to_s[5..-1].to_sym) if meth.to_s[0,5] == "from_"
+ if reader
+ self << reader.new(*args)
+ else
+ super
+ end
+ end
protected
##
@@ -184,8 +201,5 @@ def delete_statements(statements)
def delete_statement(statement)
raise NotImplementedError.new("#{self.class}#delete_statement")
end
-
- protected :delete_statements
- protected :delete_statement
end
end

0 comments on commit 3ff7ee9

Please sign in to comment.