lib/dionysus/string.rb in dionysus-0.2.1 vs lib/dionysus/string.rb in dionysus-0.3.0
- old
+ new
@@ -4,10 +4,13 @@
##
# Adds string encoding convenience methods.
#
# require 'dionysus/string'
class String
+ HEX_REGEXP = /^[a-f0-9]+$/
+ BASE64_REGEXP = /^[A-Za-z0-9\+\/\=]+$/
+
##
# Encode the Base64 (without newlines)
def encode64s() Base64.encode64s(self); end
##
@@ -25,6 +28,20 @@
##
# Decode from hexidecimal
def decode_hexidecimal() [self].pack('H*'); end
alias_method :decode_hex, :decode_hexidecimal
+
+ ##
+ # Detect the encoding of the string
+ def detect_encoding
+ return nil if blank?
+
+ if match(HEX_REGEXP)
+ :hex
+ elsif match(BASE64_REGEXP)
+ :base64
+ else
+ :binary
+ end
+ end
end