Sha256: eee35f42bb2387e491a07e9ca9cc29f039cde64ec591cd94c2659ca18c9452fa

Contents?: true

Size: 1.01 KB

Versions: 6

Compression:

Stored size: 1.01 KB

Contents

require 'dionysus'
require 'active_support/base64'

##
# Adds string encoding convenience methods.
#
#     require 'dionysus/string'
class String
  HEX_REGEXP = /^[a-f0-9]+$/
  BASE64_REGEXP = /^[A-Za-z0-9\+\/\=]+$/
  ENCODING_BITS_PER_CHAR = {:binary => 8, :base64 => 6, :hex => 4, :hexidecimal => 4}
  
  ##
  # Encode the Base64 (without newlines)
  def encode64s() Base64.encode64s(self); end
  
  ##
  # Encode to Base 64
  def encode64() Base64.encode64(self); end
  
  ##
  # Decode from Base 64
  def decode64() Base64.decode64(self); end
  
  ##
  # Encode to hexidecimal
  def encode_hexidecimal() self.unpack('H*').first; end
  alias_method :encode_hex, :encode_hexidecimal
  
  ##
  # 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

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
dionysus-1.0.2 lib/dionysus/string.rb
dionysus-1.0.1 lib/dionysus/string.rb
dionysus-1.0.0 lib/dionysus/string.rb
dionysus-0.4.0 lib/dionysus/string.rb
dionysus-0.3.2 lib/dionysus/string.rb
dionysus-0.3.1 lib/dionysus/string.rb