Skip to content

Instantly share code, notes, and snippets.

@gabeodess
Created May 5, 2015 16:44
Show Gist options
  • Save gabeodess/a78aafa82aae75909cb1 to your computer and use it in GitHub Desktop.
Save gabeodess/a78aafa82aae75909cb1 to your computer and use it in GitHub Desktop.
class String #:nodoc:
# =================
# = Class Methods =
# =================
def self.alphanumeric(length = 6)
(1..length).map{ [(0..9), ('a'..'z'), ('A'..'Z')].map(&:to_a).flatten.sample }.join
end
# ====================
# = Instance Methods =
# ====================
def encrypt(key)
cipher = OpenSSL::Cipher::AES.new(128, :CBC)
cipher.encrypt
cipher.key = key
cipher.iv = key
return Base64.urlsafe_encode64(cipher.update(self) + cipher.final)
end
def decrypt(key)
decipher = OpenSSL::Cipher::AES.new(128, :CBC)
decipher.decrypt
decipher.key = key
decipher.iv = key
return (decipher.update(Base64.urlsafe_decode64(self)) + decipher.final)
end
def split_by_any(*args)
string = self
array = string.split(args.first)
args.to_a.each do |splitter|
array = array.map{|item| item.split(splitter)}.flatten
end
return array.reject{|item| item.blank?}
end
def email?
self.match(Regex.email)
end
def zip_code?
self.match(Regex.zip_code)
end
def phone?
number = self.gsub(/[ -\.\)\(]/, '').gsub(/^1/, '')
number.match(/^\d{10}$/) and !number.match(/^[01]/)
end
# =========
# = Regex =
# =========
class Regex
def self.slug
/^[\w\d-]+$/
end
def self.email
illegals = %q{'"\[\]\(\)<>;,@# }
/^([^#{illegals}]+)?[^#{illegals}\.]@[^\.#{illegals}]([^#{illegals}]+)?\.[a-z]+$/
end
def self.login
/^[a-zA-Z0-9\-_]+$/
end
def self.zip_code
/^\d{5}$/
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment