Module: Musa::Extension::Hashify

Defined in:
lib/musa-dsl/core-ext/hashify.rb

Overview

Note:

This refinement must be activated with using Musa::Extension::Hashify

Note:

Singleton class modules (dataset extensions) are preserved on hash results

Refinement that converts objects, arrays, and hashes into hashes with specified keys.

This refinement is crucial for normalizing parameters in the DSL, especially when dealing with musical events that can be specified in multiple formats (positional, hash-based, or mixed).

Core Behavior

  • Object: Creates hash mapping all keys to the same value
  • Array: Maps keys to array elements in order (consuming array)
  • Hash: Filters and reorders according to specified keys
  • Preserves singleton class modules on hash results

Use Cases

  • Converting positional parameters to named parameters
  • Normalizing mixed parameter formats in musical events
  • Extracting specific keys from larger hashes
  • Providing defaults for missing event attributes

Methods Added

Object

  • Object#hashify - Creates a hash mapping all specified keys to this object's value

Array

  • Array#hashify - Maps array elements to hash keys in order, consuming the array

Hash

  • Hash#hashify - Filters and reorders hash to include only specified keys, preserving modules

Examples:

Basic object hashification

using Musa::Extension::Hashify

100.hashify(keys: [:velocity, :duration])
# => { velocity: 100, duration: 100 }

Array to hash

using Musa::Extension::Hashify

[60, 100, 0.5].hashify(keys: [:pitch, :velocity, :duration])
# => { pitch: 60, velocity: 100, duration: 0.5 }

Hash filtering and reordering

using Musa::Extension::Hashify

{ pitch: 60, velocity: 100, channel: 0, duration: 1 }
  .hashify(keys: [:pitch, :velocity])
# => { pitch: 60, velocity: 100 }

With defaults

using Musa::Extension::Hashify

[60].hashify(keys: [:pitch, :velocity, :duration], default: nil)
# => { pitch: 60, velocity: nil, duration: nil }

Musical event normalization

using Musa::Extension::Hashify

# User provides just a pitch
60.hashify(keys: [:pitch, :velocity], default: 64)
# => { pitch: 60, velocity: 64 }

# User provides array [pitch, velocity, duration]
[62, 90, 0.5].hashify(keys: [:pitch, :velocity, :duration])
# => { pitch: 62, velocity: 90, duration: 0.5 }

See Also: