Sha256: 2acfd612f95dcda685004c322b234ed0125774e20a821918b0ba80a8c4157aa7

Contents?: true

Size: 1.66 KB

Versions: 1

Compression:

Stored size: 1.66 KB

Contents

# frozen_string_literal: true

# A placement is a note or rest at a position within a voice in a composition
class HeadMusic::Placement
  include Comparable

  attr_reader :voice, :position, :rhythmic_value, :pitch
  delegate :composition, to: :voice
  delegate :spelling, to: :pitch, allow_nil: true

  def initialize(voice, position, rhythmic_value, pitch = nil)
    ensure_attributes(voice, position, rhythmic_value, pitch)
  end

  def note?
    pitch
  end

  def rest?
    !note?
  end

  def next_position
    @next_position ||= position + rhythmic_value
  end

  def <=>(other)
    position <=> other.position
  end

  def during?(other_placement)
    starts_during?(other_placement) || ends_during?(other_placement) || within?(other_placement)
  end

  def to_s
    "#{pitch ? pitch : 'rest'} at #{position}"
  end

  private

  def starts_during?(other_placement)
    (other_placement.next_position > position && other_placement.next_position <= next_position)
  end

  def ends_during?(other_placement)
    (other_placement.position >= position && other_placement.position < next_position)
  end

  def within?(other_placement)
    (other_placement.position <= position && other_placement.next_position >= next_position)
  end

  def ensure_attributes(voice, position, rhythmic_value, pitch)
    @voice = voice
    ensure_position(position)
    @rhythmic_value = HeadMusic::RhythmicValue.get(rhythmic_value)
    @pitch = HeadMusic::Pitch.get(pitch)
  end

  def ensure_position(position)
    @position = if position.is_a?(HeadMusic::Position)
                  position
                else
                  HeadMusic::Position.new(composition, position)
                end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
head_music-0.18.0 lib/head_music/placement.rb