Class: URN

Inherits:
Object
  • Object
show all
Defined in:
lib/urn.rb

Constant Summary collapse

InvalidURNError =
Class.new(StandardError)
PATTERN =
%{(?i:urn:(?!urn:)[a-z0-9][a-z0-9\-]{1,31}:} +
%{(?:[a-z0-9()+,-.:=@;$_!*']|%(?:2[1-9a-f]|[3-6][0-9a-f]|7[0-9a-e]))+)}.freeze
REGEX =
/\A#{PATTERN}\z/

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(urn) ⇒ URN

Returns a new instance of URN.



21
22
23
24
25
26
27
# File 'lib/urn.rb', line 21

def initialize(urn)
  urn = urn.to_s
  fail InvalidURNError, "bad URN(is not URN?): #{urn}" if urn !~ REGEX

  @urn = urn
  _scheme, @nid, @nss = urn.split(':', 3)
end

Instance Attribute Details

#nidObject (readonly)

Returns the value of attribute nid.



14
15
16
# File 'lib/urn.rb', line 14

def nid
  @nid
end

#nssObject (readonly)

Returns the value of attribute nss.



14
15
16
# File 'lib/urn.rb', line 14

def nss
  @nss
end

Class Method Details

.extract(str, &blk) ⇒ Object



17
18
19
# File 'lib/urn.rb', line 17

def self.extract(str, &blk)
  str.scan(/\b#{PATTERN}/, &blk)
end

Instance Method Details

#==(other) ⇒ Object



54
55
56
57
58
# File 'lib/urn.rb', line 54

def ==(other)
  return false unless other.is_a?(URN)

  normalize.to_s == other.normalize.to_s
end

#===(other) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/urn.rb', line 40

def ===(other)
  if other.respond_to?(:normalize)
    urn_string = other.normalize.to_s
  else
    begin
      urn_string = URN.new(other).normalize.to_s
    rescue URN::InvalidURNError
      return false
    end
  end

  normalize.to_s == urn_string
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


60
61
62
63
64
# File 'lib/urn.rb', line 60

def eql?(other)
  return false unless other.is_a?(URN)

  to_s == other.to_s
end

#normalizeObject



29
30
31
32
33
34
# File 'lib/urn.rb', line 29

def normalize
  normalized_nid = nid.downcase
  normalized_nss = nss.gsub(/%([0-9a-f]{2})/i) { |hex| hex.downcase }

  URN.new("urn:#{normalized_nid}:#{normalized_nss}")
end

#to_sObject



36
37
38
# File 'lib/urn.rb', line 36

def to_s
  urn
end