mbj / devtools

The rake ci task!
MIT License
64 stars 20 forks source link

Assert config file field types #96

Closed backus closed 9 years ago

backus commented 9 years ago

91 refactored the flay implementation and killed some mutations along the way. An unintended side effect was that configuration that specifies total_score as a float like so


---
threshold: 12
total_score: 88.0

as opposed to an integer


---
threshold: 12
total_score: 88

now produces

Flay total is now 88, but expected 88 bundle exec rake ci returned exit code 1

To avoid issues like this, we should assert expected types on configuration load.

backus commented 9 years ago

As an intermediary fix before config is rewritten with morpher, we could rewrite the Devtools::Config.attribute to read

Undefined = Class.new(Object)

# Declare an attribute
#
# @param [Symbol] name
#
# @yieldreturn [Object]
#   the default value to use
#
# @api private
#
# @return [self]
#
def self.attribute(name, *types, default: Undefined.new)
  define_method(name) do
    assert_attribute_type(raw.fetch(name.to_s, default), types)
  end
end
private_class_method :attribute

# Assert value is an expected type
#
# @param value [Object] loaded attribute value
# @param types [Array<Class>] allowed types
#
# @raise [TypeError] if invalid type
# @return value otherwise
#
# @api private
def self.assert_attribute_type(value, types)
  fail TypeError, value unless types.any?(&value.method(:instance_of?))

  value
end
private_class_method :assert_attribute_type

in which case an attribute definition would read like so

attribute :zombify, [TrueClass, FalseClass], default: false
mbj commented 9 years ago

@backus This was fixed with #104