Created
January 1, 2012 22:18
-
-
Save coryschires/1548498 to your computer and use it in GitHub Desktop.
Cucumber helper method which makes it easier to work with tabular data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Starts with cucumber's built-in hashes method and adds a bit more magic: | |
# | |
# * Converts hash keys from stings to symbols | |
# * Converts numeric values into integers | |
# * Converts true/false strings into actual booleans | |
# | |
def hasherize(table) | |
table.hashes.map do |object| | |
object.each do |attribute, value| | |
object[attribute] = to_boolean?(value) | |
object[attribute] = to_integer?(object[attribute]) | |
object[symbolize(attribute)] = object.delete(attribute) unless attribute.is_a?(Symbol) | |
end | |
end | |
end | |
private | |
# Converts human readable attribute names (e.g. 'transaction type') into rails-ready | |
# symbolized hash keys (e.g. :transaction type). | |
# | |
def symbolize(string) | |
string.parameterize.underscore.to_sym | |
end | |
# Checks if the passed value contains only digits and underscores. | |
# | |
def to_integer?(value) | |
value.is_a?(String) && value.match(/^[\d_]+$/) ? value.to_i : value | |
end | |
# Converts true/false/t/f strings into proper booleans. | |
# | |
def to_boolean?(value) | |
value.is_a?(String) && value.strip.match(/^(t|f|true|false)$/i) ? !!(value =~ /t|true/i) : value | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment