Class: HeadMusic::Rudiment::Pitch::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/head_music/rudiment/pitch/parser.rb

Constant Summary collapse

LetterName =
HeadMusic::Rudiment::LetterName
Alteration =
HeadMusic::Rudiment::Alteration
Spelling =
HeadMusic::Rudiment::Spelling
Register =
HeadMusic::Rudiment::Register
Pitch =
HeadMusic::Rudiment::Pitch
PATTERN =

Pattern that handles negative registers (e.g., -1) and positive registers Anchored to match complete pitch strings only

/\A(#{LetterName::PATTERN})?(#{Alteration::PATTERN.source})?(-?\d+)?\z/

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(identifier) ⇒ Parser

Returns a new instance of Parser.



21
22
23
24
# File 'lib/head_music/rudiment/pitch/parser.rb', line 21

def initialize(identifier)
  @identifier = identifier.to_s.strip
  parse_components
end

Instance Attribute Details

#alterationObject (readonly)

Returns the value of attribute alteration.



2
3
4
# File 'lib/head_music/rudiment/pitch/parser.rb', line 2

def alteration
  @alteration
end

#identifierObject (readonly)

Returns the value of attribute identifier.



2
3
4
# File 'lib/head_music/rudiment/pitch/parser.rb', line 2

def identifier
  @identifier
end

#letter_nameObject (readonly)

Returns the value of attribute letter_name.



2
3
4
# File 'lib/head_music/rudiment/pitch/parser.rb', line 2

def letter_name
  @letter_name
end

#registerObject (readonly)

Returns the value of attribute register.



2
3
4
# File 'lib/head_music/rudiment/pitch/parser.rb', line 2

def register
  @register
end

Class Method Details

.parse(identifier) ⇒ Object

Parse a pitch identifier and return a Pitch object Returns nil if the identifier cannot be parsed into a valid pitch



16
17
18
19
# File 'lib/head_music/rudiment/pitch/parser.rb', line 16

def self.parse(identifier)
  return nil if identifier.nil?
  new(identifier).pitch
end

Instance Method Details

#parse_componentsObject (private)



43
44
45
46
47
48
49
50
51
# File 'lib/head_music/rudiment/pitch/parser.rb', line 43

def parse_components
  match = identifier.match(PATTERN)

  if match
    @letter_name = LetterName.get(match[1].upcase) unless match[1].to_s.empty?
    @alteration = Alteration.get(match[2] || "") unless match[2].to_s.empty?
    @register = Register.get(match[3]&.to_i) unless match[3].to_s.empty?
  end
end

#pitchObject



26
27
28
29
30
31
32
33
# File 'lib/head_music/rudiment/pitch/parser.rb', line 26

def pitch
  return unless spelling
  # Default to register 4 if not provided (matching old behavior)
  # Convert Register object to integer for fetch_or_create
  reg = register ? register.to_i : Register::DEFAULT

  @pitch ||= Pitch.fetch_or_create(spelling, reg)
end

#spellingObject



35
36
37
38
39
# File 'lib/head_music/rudiment/pitch/parser.rb', line 35

def spelling
  return unless letter_name

  @spelling ||= Spelling.new(letter_name, alteration)
end