Module: RDF::Namespace

Defined in:
lib/rdf/namespace.rb

Overview

An RDF namespace that can be used to generate URI references easily.

Example:

RDF::Namespace.register(:ex, 'http://example.com/')
EX::Test   #=> 'http://example.com/Test'
EX::test   #=> 'http://example.com/test'

Constant Summary collapse

@@prefixes =
{}
@@bases =
{}

Class Method Summary collapse

Class Method Details

.expand(prefix, name) ⇒ Object

Returns the string resulting from looking up the prefix and appending the name



57
58
59
60
# File 'lib/rdf/namespace.rb', line 57

def expand(prefix, name)
  prefix, name = prefix.to_s.downcase.to_sym, name.to_s
  @@prefixes[prefix] + name
end

.prefix(uri) ⇒ Object

Returns the assigned prefix name for a uri, if one exists



70
71
72
# File 'lib/rdf/namespace.rb', line 70

def prefix(uri)
  @@bases[split(uri).first]
end

.prefixesObject

Returns an array of all registered prefixes.



15
16
17
# File 'lib/rdf/namespace.rb', line 15

def prefixes
  @@prefixes.keys
end

.register(prefix, base) ⇒ Object

Registers prefix as a nickname for base, and either finds an existing module, or creates a new module named prefix that can be used for expansions.

Raises:

  • (ArgumentError)


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/rdf/namespace.rb', line 26

def register(prefix, base)
  raise ArgumentError, "prefix cannot be nil" if prefix.to_s.empty?
  
  prefix, base = prefix.to_s.to_sym, base.to_s
  
  raise ArgumentError, "base is invalid it should end with '/' or '#'" unless ['/', '#'].include?(base[-1,1])
  if @@prefixes.has_key?(prefix)
    $stderr.puts "Warning: Namespace #{prefix} is already defined"
    return find_or_create_module(prefix)
  end
  
  @@prefixes[prefix] = base
  @@bases[base] = prefix
  
  mod = find_or_create_module(prefix)
  class << mod
    def method_missing(sym, *a, &b)
      raise ArgumentError, "Unexpected arguments for Namespace.expand" if a.size > 0
      RDF::UriNode.new(Namespace.expand(self, sym))
    end
    
    def const_missing(sym)
      RDF::UriNode.new(Namespace.expand(self, sym))
    end
    
    [:type, :name, :id].each{|a| private(a)}
  end
  mod
end

.registered?(prefix) ⇒ Boolean

Returns true if the specified prefix is registered.

Returns:

  • (Boolean)


20
21
22
# File 'lib/rdf/namespace.rb', line 20

def registered?(prefix)
  @@prefixes.key?(prefix)
end

.split(uri) ⇒ Object

Finds the last ‘/’ or ‘#’ and uses it to split the uri into base and name parts.



63
64
65
66
67
# File 'lib/rdf/namespace.rb', line 63

def split(uri)
  uri = uri.to_s
  i = uri.rindex(/\/|#/) + 1
  [uri[0...i].to_s, uri[i..-1].to_s]
end