Created
January 13, 2010 11:00
-
-
Save moustaki/276106 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module RDFMapper | |
class << self | |
def to_rdf(obj) | |
mapping = obj.rdf_mapping | |
uri = obj.uri | |
data = "<#{uri}>\n" unless mapping.empty? | |
data = self.parse_mapping(data, mapping, obj) | |
if (doc_uri = obj.doc_uri) && (obj.respond_to? :updated_at) && (obj.respond_to? :created_at) | |
data += "<#{doc_uri}> a foaf:Document; dc:created \"#{obj.created_at.iso8601}\"^^xsd:dateTime; dc:modified \"#{obj.updated_at.iso8601}\"^^xsd:dateTime .\n\n" | |
end | |
data | |
end | |
def parse_mapping(data, mapping, obj) | |
unless mapping.empty? | |
data += "a #{mapping[:type]};\n" | |
mapping.keys.each do |key| | |
unless key == :type | |
if (value = obj.send(key)) && (value != "") && (value.class != Array) | |
value = self.rdf_value(value, obj) | |
if mapping[key].class != Array | |
data += "#{mapping[key]} #{value};\n" unless key == :type | |
else | |
mapping[key].each do |k| | |
data += "#{k} #{value};\n" unless key == :type | |
end | |
end | |
elsif value.class == Array | |
value.each do |v| | |
v = self.rdf_value(v, obj) | |
data += "#{mapping[key]} #{v};\n" unless key == :type | |
end | |
end | |
end | |
end | |
data = data[0, data.length - 2] + ".\n\n" # Getting rid of the previous ; | |
end | |
end | |
def rdf_value(value, obj) | |
if value.class == String | |
value = value.gsub('"', '\"') | |
value = "\"\"\"#{value}\"\"\"^^xsd:string" | |
elsif value.class == Fixnum | |
value = "\"#{value}\"^^xsd:int" | |
elsif value.class == Float | |
value = "\"#{value}\"^^xsd:float" | |
elsif value.class == URI::HTTP | |
value = "<#{value.to_s}>" | |
elsif value.class == Hash | |
data = parse_mapping("", value, obj) | |
data = data[0, data.length - 3] # Removing the last . | |
value = "[ #{data} ]" | |
elsif value.class == Date | |
value = "\"#{value.to_s}\"^^xsd:date" | |
elsif value.class == DateTime | |
value = "\"#{value.to_s}\"^^xsd:dateTime" | |
elsif value.class == Time | |
value = "\"#{value.iso8601}\"^^xsd:dateTime" | |
elsif value_uri = value.uri | |
value = "<#{value_uri}>" | |
end | |
value | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment