Skip to content

Instantly share code, notes, and snippets.

@coryschires
Created January 1, 2012 22:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coryschires/1548498 to your computer and use it in GitHub Desktop.
Save coryschires/1548498 to your computer and use it in GitHub Desktop.
Cucumber helper method which makes it easier to work with tabular data
# 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