Permalink
Browse files

Exposed PitchClass.[] and made it take a single argument (name) inste…

…ad of name,value.

This makes the interface more consistent with Pitch and cleans up some evaluation logic in the grammar.
  • Loading branch information...
1 parent 1816a0d commit 0604eeeb836d5bb20b4eafc95e0626dbfa72896e @adamjmurray committed Jul 5, 2011
Showing with 27 additions and 21 deletions.
  1. +12 −14 lib/mtk/pitch_class.rb
  2. +15 −7 spec/mtk/pitch_class_spec.rb
View
26 lib/mtk/pitch_class.rb
@@ -34,29 +34,27 @@ def initialize(name, int_value)
@flyweight = {}
- # Return a new object, only constructing a new instance when not already in the flyweight cache
- def self.[](name, value)
- @flyweight[name] ||= new(name, value) if VALID_NAMES.include? name
- end
- private_class_method :[]
-
- def self.from_s(s)
- s = s.to_s
- s = s[0..0].upcase + s[1..-1].downcase # normalize the name
+ # Lookup a PitchClass by name.
+ # @param name [String, #to_s] one of the values in {VALID_NAMES}
+ def self.[](name)
+ name = name.to_s
+ name = name[0..0].upcase + name[1..-1].downcase # normalize the name
VALID_NAMES_BY_VALUE.each_with_index do |names, value|
- return self[s, value] if names.include? s
+ if names.include? name
+ return @flyweight[name] ||= new(name, value)
+ end
end
nil
end
class << self
- alias from_name from_s # alias self.from_name to self.from_s
+ alias :from_s :[]
+ alias :from_name :[]
end
def self.from_i(value)
- value = value.to_i % 12
- name = NAMES[value]
- self[name, value]
+ name = NAMES[value.to_i % 12]
+ self[name]
end
def == other
View
22 spec/mtk/pitch_class_spec.rb
@@ -48,29 +48,37 @@
describe '.from_s' do
context "the argument is a valid name" do
it "returns a PitchClass" do
- names.each { |name| PitchClass.from_s(name).should be_a PitchClass }
+ names.each { |name| PitchClass[name].should be_a PitchClass }
end
it "returns an object with that name" do
- names.each { |name| PitchClass.from_s(name).name.should == name }
+ names.each { |name| PitchClass[name].name.should == name }
end
it "ignores case" do
for name in names
- PitchClass.from_s(name.upcase).name.should == name
- PitchClass.from_s(name.downcase).name.should == name
+ PitchClass[name.upcase].name.should == name
+ PitchClass[name.downcase].name.should == name
end
end
end
context "the argument is not a valid name" do
it "returns nil, if the name doesn't exist" do
- PitchClass.from_s('z').should be_nil
+ PitchClass['z'].should be_nil
+ end
+ end
+ end
+
+ describe '.from_s' do
+ it "acts like .[]" do
+ for name in ['C', 'bbb', 'z']
+ PitchClass.from_s(name).should == PitchClass[name]
end
end
end
describe '.from_name' do
- it "acts like from_s" do
+ it "acts like .[]" do
for name in ['C', 'bbb', 'z']
- PitchClass.from_name(name).should == PitchClass.from_s(name)
+ PitchClass.from_name(name).should == PitchClass[name]
end
end
end

0 comments on commit 0604eee

Please sign in to comment.