DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
To_sub_domain
Converts any string into something that could be used as a sub domain
Usage:
"asdf as dfa sdf dsf".to_sub_domain
"asdf-as-dfa-sdf-dsf"
#object_mixins.rb
class Object
def to_sub_domain
#thanks to kipp howard for the much more readable regex tips
#convert spaces to "-"
a = /\s/
#remove leading and trailing "-"
#b = /^-*([a-z0-9][a-z0-9\-]{0,}[a-z0-9]{1})-*$/
b = /^-*(\w+[a-z0-9\-]*\w)-*$/
#remove all other characters
c = /[^a-z0-9\-]/
#remove all -------
d = /^-*$/
self.to_s.strip.downcase.gsub(a,'-').gsub(b,'\1').gsub(c,'').gsub(b,'\1').gsub(d,'')
end
end
Rspec tests
# -*- coding: utf-8 -*-
require File.dirname(__FILE__) + '/../spec_helper'
require 'object_mixins'
def bad_sub_domains
[" asdf ", "$92sadf-94%", "*", "", " ", "----", "asdf ", " - ", "-", "this quick brown fox, ran up the hill", "\n",
" - asdf-eieie%% pwpwp f------------ ", "-asdf-", "asdf-", "-asdf"]
end
def bad_sub_domains_converted
["asdf", "92sadf-94", "", "", "", "", "asdf", "", "", "this-quick-brown-fox-ran-up-the-hill", "",
"asdf-eieie--pwpwp----f", "asdf", "asdf", "asdf"]
end
def good_sub_domains
["123", "123-123", "a1", "a", "1", "a-a", "i-am-10-feet-short"]
end
describe 'Test to_sub_domain in object_mixins' do
bad_sub_domains.each do |s|
it "should convert [#{s}] to [#{bad_sub_domains_converted[bad_sub_domains.index(s)]}]" do
#puts "[#{s.to_sub_domain}] to [#{bad_sub_domains_converted[bad_sub_domains.index(s)]}]"
assert s.to_sub_domain == bad_sub_domains_converted[bad_sub_domains.index(s)]
end
end
end





