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, extension) ⇒ Spec

Returns a new instance of Spec.



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

def initialize(marshalers, extension)
  @marshalers = marshalers
  @extension = extension
  @matcher = build_matcher

  marshalers.freeze
  freeze
end

Instance Attribute Details

#extensionObject (readonly)

Returns the value of attribute extension.



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

def extension
  @extension
end

#marshalersObject (readonly)

Returns the value of attribute marshalers.



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

def marshalers
  @marshalers
end

#matcherObject (readonly)

Returns the value of attribute matcher.



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

def matcher
  @matcher
end

Instance Method Details

#matches?(string) ⇒ Boolean

Returns:

  • (Boolean)


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

def matches?(string)
  string =~ matcher
end

#read(string) ⇒ Object

Raises:

  • (ArgumentError)


25
26
27
28
29
30
# File 'lib/key_value_name/spec.rb', line 25

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

#write(name) ⇒ Object



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

def write(name)
  string = name.each_pair.map do |key, value|
    value_string = marshalers[key].write(value)
    "#{key}#{KEY_VALUE_SEPARATOR}#{value_string}"
  end.join(PAIR_SEPARATOR)
  string += ".#{extension}" unless extension.nil?
  string
end