lib/triad.rb in triad-0.1.3 vs lib/triad.rb in triad-0.2.0
- old
+ new
@@ -3,13 +3,11 @@
class Triad
include Enumerable
class InvalidAddition < StandardError; end
- class ValueNotPresent < StandardError; end
- class DescriptorNotPresent < StandardError; end
- class KeyNotPresent < StandardError; end
+ class ItemNotPresent < StandardError; end
# stored as {key => ['Descriptor', value]}
def initialize(*args)
@storage = ThreadSafe::Hash.new
end
@@ -39,16 +37,16 @@
with_interest(arg).map{|_, _, value| value }
end
end
def <<(array)
- array_key = array.find{|item| item.is_a?(Symbol) }
+ array_key = array[0]
raise InvalidAddition.new("your array length must be 3") if array.length != 3
raise InvalidAddition.new("the provided key already exists") if key_exists?(array_key)
- array_descriptor = array.find{|item| item.is_a?(String) }
- array_value = array.find{|item| !item.is_a?(String) && !item.is_a?(Symbol) }
+ array_descriptor = array[1]
+ array_value = array[2]
storage[array_key] = [array_descriptor, array_value]
self
end
@@ -65,37 +63,31 @@
private
def key_exists?(key)
storage.has_key?(key)
end
-
- def positions
- [:key, :descriptor, :value]
+
+ def descriptor_exists?(descriptor)
+ storage.values.map{|arr| arr[0] }.include?(descriptor)
end
-
- def argument_type(arg)
- case arg
- when Symbol then :key
- when String then :descriptor
- else :value
- end
+
+ def value_exists?(value)
+ storage.values.map{|arr| arr[1] }.include?(value)
end
- def raise_error(type)
- error_name = type.to_s.gsub(/(?:^|_)([a-z])/) { $1.upcase }
- error_class = Triad.const_get("#{error_name}NotPresent")
- raise error_class.new
- end
-
def with_interest(interest)
- type = argument_type(interest)
- index = positions.index(type)
+ index = case
+ when key_exists?(interest)
+ 0
+ when descriptor_exists?(interest)
+ 1
+ when value_exists?(interest)
+ 2
+ else
+ raise ItemNotPresent.new
+ end
- lookup = storage.select{|key, array|
+ storage.select{|key, array|
[key, *array][index] == interest
}.map{|key, array| [key, *array] }
-
- raise_error(type) if lookup.empty?
-
- lookup
end
end