Class: KeyValueName::Spec

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

Overview

Specify the keys and value types for a KeyValueName.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(marshalers, prefix = nil, suffix = nil) ⇒ Spec

Returns a new instance of Spec.



8
9
10
11
12
13
14
15
16
# File 'lib/key_value_name/spec.rb', line 8

def initialize(marshalers, prefix = nil, suffix = nil)
  @marshalers = marshalers
  @prefix = prefix
  @suffix = suffix
  @matcher = build_matcher

  marshalers.freeze
  freeze
end

Instance Attribute Details

#marshalersObject (readonly)

Returns the value of attribute marshalers.



18
19
20
# File 'lib/key_value_name/spec.rb', line 18

def marshalers
  @marshalers
end

#matcherObject (readonly)

Returns the value of attribute matcher.



21
22
23
# File 'lib/key_value_name/spec.rb', line 21

def matcher
  @matcher
end

#prefixObject (readonly)

Returns the value of attribute prefix.



19
20
21
# File 'lib/key_value_name/spec.rb', line 19

def prefix
  @prefix
end

#suffixObject (readonly)

Returns the value of attribute suffix.



20
21
22
# File 'lib/key_value_name/spec.rb', line 20

def suffix
  @suffix
end

Instance Method Details

#compare(a, b) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/key_value_name/spec.rb', line 50

def compare(a, b)
  return 0 if a.nil? && b.nil?
  return nil if a.nil? || b.nil?
  a.each_pair do |key, value|
    marshaler = marshalers[key]
    a_comparable = marshaler.to_comparable(value)
    b_comparable = marshaler.to_comparable(b[key])
    signum = a_comparable <=> b_comparable
    return signum if signum != 0
  end
  0
end

#generate(struct) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/key_value_name/spec.rb', line 42

def generate(struct)
  body = struct.each_pair.map do |key, value|
    value_string = marshalers[key].generate(value)
    "#{key}#{KEY_VALUE_SEPARATOR}#{value_string}"
  end.join(PAIR_SEPARATOR)
  "#{prefix}#{body}#{suffix}"
end

#globObject



27
28
29
30
31
32
33
# File 'lib/key_value_name/spec.rb', line 27

def glob
  if marshalers.any?
    "#{prefix}*#{suffix}"
  else
    "#{prefix}#{suffix}"
  end
end

#matches?(basename) ⇒ Boolean

Returns:

  • (Boolean)


23
24
25
# File 'lib/key_value_name/spec.rb', line 23

def matches?(basename)
  basename =~ matcher
end

#parse(basename) ⇒ Object

Raises:

  • (ArgumentError)


35
36
37
38
39
40
# File 'lib/key_value_name/spec.rb', line 35

def parse(basename)
  raise ArgumentError, "bad name: #{basename}" unless matcher =~ basename
  Hash[marshalers.map.with_index do |(key, marshaler), index|
    [key, marshaler.parse(Regexp.last_match(index + 1))]
  end]
end