Created
January 5, 2011 06:00
-
-
Save matsuda/765989 to your computer and use it in GitHub Desktop.
hash_with_underscore_key is only converting key on Hash into underscore.
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
class Array | |
def to_underscore_key | |
self.class.new.tap do |array| | |
self.each { |value| | |
case value | |
when Hash, Array | |
array << value.to_underscore_key | |
else | |
array << value | |
end | |
} | |
end | |
end | |
end |
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
class Hash | |
def to_underscore_key | |
self.class.new.tap do |hash| | |
self.each_pair { |key, value| | |
case key | |
when Hash, Array, String, Symbol | |
case value | |
when Hash, Array | |
hash[key.to_underscore_key] = value.to_underscore_key | |
else | |
hash[key.to_underscore_key] = value | |
end | |
else | |
case value | |
when Hash, Array | |
hash[key] = value.to_underscore_key | |
else | |
hash[key] = value | |
end | |
end | |
} | |
end | |
end | |
end |
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
class String | |
def to_underscore_key | |
self.underscore.gsub(/([^\d\s]+)(\d)/, "\\1_\\2") | |
end | |
end |
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
class Symbol | |
def to_underscore_key | |
self.to_s.to_underscore_key.to_sym | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment