Module: XRB::Strings

Defined in:
lib/xrb/strings.rb

Overview

String transformation helpers used when generating markup and identifiers.

Constant Summary collapse

HTML_ESCAPE =
{"&" => "&amp;", "<" => "&lt;", ">" => "&gt;", "\"" => "&quot;"}
HTML_ESCAPE_PATTERN =
Regexp.new("[" + Regexp.quote(HTML_ESCAPE.keys.join) + "]")

Class Method Summary collapse

Class Method Details

.to_attribute(key, value) ⇒ Object

value must already be escaped.



31
32
33
# File 'lib/xrb/strings.rb', line 31

def self.to_attribute(key, value)
	%Q{#{key}="#{value}"}
end

.to_html(string) ⇒ Object

Escape HTML-sensitive characters in a string.



15
16
17
# File 'lib/xrb/strings.rb', line 15

def self.to_html(string)
	string.gsub(HTML_ESCAPE_PATTERN){|c| HTML_ESCAPE[c]}
end

.to_quoted_string(string) ⇒ Object

Quote a string and escape quotes and line breaks within it.



22
23
24
25
26
27
28
# File 'lib/xrb/strings.rb', line 22

def self.to_quoted_string(string)
	string = string.gsub('"', '\\"')
	string.gsub!(/\r/, "\\r")
	string.gsub!(/\n/, "\\n")
	
	return "\"#{string}\""
end

.to_simple_attribute(key, strict) ⇒ Object

Format a boolean-style attribute.



39
40
41
# File 'lib/xrb/strings.rb', line 39

def self.to_simple_attribute(key, strict)
	strict ? %Q{#{key}="#{key}"} : key.to_s
end

.to_snake(string) ⇒ Object

Convert a constant-like name to a snake-case identifier.



56
57
58
59
60
61
62
# File 'lib/xrb/strings.rb', line 56

def self.to_snake(string)
	string = string.gsub("::", "")
	string.gsub!(/([A-Z]+)/){"_" + $1.downcase}
	string.sub!(/^_+/, "")
	
	return string
end

.to_title(string) ⇒ Object

Convert a separated identifier to a human-readable title.



46
47
48
49
50
51
# File 'lib/xrb/strings.rb', line 46

def self.to_title(string)
	string = string.gsub(/(^|[ \-_])(.)/){" " + $2.upcase}
	string.strip!
	
	return string
end