module WebUtils

Constants

ACCENTS
ALPHA_NUM_RE
AMPERSAND
AND_STRING
ARG1_SUB
BLANK_RE

From then on, constants preceed the methods they are used on.

BOT_REGEX
BR_TAG
COMMA
COMMA_BASED_PRICE_RE
CONST_SEP
DASH
DASHIFY_RE
DASH_LOWER_OR_NUM_RE
DEFAULT_BRAND
DEPRECATED_RANDOM_ID_STRING
DOT
EACH_STUB_ERR_MSG
EDGE_DASH_RE
ELLIPSIS
EMAIL_REGEX
EMPTY_STRING

Global string constants

E_STRING
FALSE_STRING
FLOAT_RE
ID_CHARS
ID_SIZE
IES_STRING
INT_RE
NL_RE
NON_PRICE_CHARS_RE
NO_CENTS_RE
PERCENT
PIPE
PLURAL_RE
PLURAL_SUB
PRICE_ERR_MSG
PRICE_FMT
PRICE_PARSE_ERR_MSG
QUERY_SPLITTER
RN_RE
SINGULAR_RE
SPACE
SPACE_PERCENT_STRING
START_DOT_SLASH_RE
START_LOWER_RE
START_UPPER_RE
SWITCH_DOT_COMMA_TR
S_STRING
TAG_REGEX
THOUSANDS_RE
THOUSANDS_SUB
TRUE_STRING
TYPECASTABLE
UNDERSCORE
UPPER_OR_NUM_RE
VERSION
WITHOUT_ACCENTS
XES_STRING
X_STRING
Y_STRING

Public Class Methods

automatic_html(s, br=BR_TAG) click to toggle source
# File lib/web_utils.rb, line 267
def automatic_html s, br=BR_TAG
  replaced = s.to_s.
  gsub(LINK_REGEX) do |str|
    url = complete_link $1
    "<a href='#{url}' target='_blank'>#{$1}</a>"
  end.
  gsub(EMAIL_REGEX) do |str|
    "<a href='mailto:#{$1.downcase}'>#{$1}</a>"
  end
  nl2br(replaced,br)
end
automatic_typecast(str, casted=TYPECASTABLE) click to toggle source
# File lib/web_utils.rb, line 199
def automatic_typecast str, casted=TYPECASTABLE 
  return str unless str.is_a?(String)
  casted = casted.map do |sym|
    case sym
    when :int
      :integer
    when :bool
      :boolean
    else
      sym
    end
  end
  if casted.include?(:boolean) and str == TRUE_STRING
    true
  elsif casted.include?(:boolean) and str == FALSE_STRING
    false
  elsif casted.include?(:nil) and str == EMPTY_STRING
    nil
  elsif casted.include?(:integer) and str =~ INT_RE
    str.to_i
  elsif casted.include?(:float) and str =~ FLOAT_RE
    str.to_f
  else
    str
  end
end
being_crawled?(request) click to toggle source
# File lib/web_utils.rb, line 361
def being_crawled? request
  request.user_agent =~ BOT_REGEX
end
blank?(s) click to toggle source
# File lib/web_utils.rb, line 47
def blank? s
  return true if s.nil?
  # Not much difference with strip on benchmarks
  # return (s.empty? or BLANK_RE.match?(s)) if s.is_a?(String)
  return (s.strip.empty?) if s.is_a?(String)
  return s.empty? if s.respond_to?(:empty?)
  return true if s==false
  false
end
branded_filename(path, brand=DEFAULT_BRAND) click to toggle source
# File lib/web_utils.rb, line 340
def branded_filename path, brand=DEFAULT_BRAND
  "#{File.dirname(path)}/#{brand}-#{File.basename(path)}"
    .sub(START_DOT_SLASH_RE, EMPTY_STRING)
end
dasherize_class_name(s) click to toggle source
# File lib/web_utils.rb, line 86
def dasherize_class_name s
  s.gsub(UPPER_OR_NUM_RE) {|str| "-#{str.downcase}" }[1..-1].gsub(CONST_SEP, DASH)
end
deep_copy(original) click to toggle source
# File lib/web_utils.rb, line 141
def deep_copy original
  Marshal.load(Marshal.dump(original))
end
display_price(int) click to toggle source
# File lib/web_utils.rb, line 307
def display_price int
  unless int.is_a?(Integer)
    raise(TypeError, PRICE_ERR_MSG)
  end
  (PRICE_FMT % (int/100.0))
    .sub(NO_CENTS_RE, EMPTY_STRING)
    .reverse
    .gsub(THOUSANDS_RE, THOUSANDS_SUB)
    .reverse
end
each_stub(obj, &block) click to toggle source
# File lib/web_utils.rb, line 182
def each_stub obj, &block 
  raise TypeError, EACH_STUB_ERR_MSG unless obj.respond_to?(:each_with_index)
  obj.each_with_index do |(k,v),i|
    value = v || k
    if value.is_a?(Hash) || value.is_a?(Array)
      each_stub(value,&block)
    else
      block.call(obj, (v.nil? ? i : k), value)
    end
  end
end
ensure_key(h, k, v) click to toggle source
# File lib/web_utils.rb, line 151
def ensure_key h, k, v
  {k=>v}.merge h
end
ensure_key!(h, k, v) click to toggle source
# File lib/web_utils.rb, line 146
def ensure_key! h, k, v
  h.fetch(k) {|k| h.store(k, v) }
end
filename_variation(path, variation, ext) click to toggle source
# File lib/web_utils.rb, line 346
def filename_variation path, variation, ext
  old_ext = File.extname(path) 
  path.sub(/#{Regexp.escape old_ext}$/, ".#{variation}.#{ext}")
end
generate_random_id(size=ID_SIZE) click to toggle source
# File lib/web_utils.rb, line 231
def generate_random_id size=ID_SIZE
  warn DEPRECATED_RANDOM_ID_STRING
  id = String.new
  size.times{id << ID_CHARS[rand(ID_CHARS.size)]} 
  id
end
get_value(raw, context=Kernel) click to toggle source
# File lib/web_utils.rb, line 130
def get_value raw, context=Kernel
  if raw.is_a? Proc
    raw.call
  elsif raw.is_a? Symbol
    context.__send__ raw
  else
    raw
  end
end
h(text) click to toggle source
# File lib/web_utils.rb, line 366
def h text
  escape_html text
end
initial_request?(request) click to toggle source
# File lib/web_utils.rb, line 352
def initial_request? request
  URI.parse(request.referer).host!=request.host
rescue URI::InvalidURIError
  return true
end
label_for_field(field_name) click to toggle source
# File lib/web_utils.rb, line 175
def label_for_field field_name
  field_name.to_s.scan(ALPHA_NUM_RE).map(&:capitalize).join(SPACE)
end
nl2br(s, br=BR_TAG) click to toggle source
# File lib/web_utils.rb, line 241
def nl2br s, br=BR_TAG
  s.to_s.gsub(RN_RE, br)
end
parse_price(string) click to toggle source
# File lib/web_utils.rb, line 324
def parse_price string
  unless string.is_a?(String)
    raise(TypeError, PRICE_PARSE_ERR_MSG) 
  end
  string = string.gsub(NON_PRICE_CHARS_RE, EMPTY_STRING)
  if string[COMMA_BASED_PRICE_RE]
    # comma-based price
    string = string.tr(*SWITCH_DOT_COMMA_TR)
  end
  (PRICE_FMT % string.gsub(COMMA, EMPTY_STRING)).gsub(DOT, EMPTY_STRING).to_i
end
pluralize(s) click to toggle source
# File lib/web_utils.rb, line 61
def pluralize s
  s = s.dup
  s<<E_STRING if s[-1,1]==X_STRING
  s<<S_STRING
  s.sub PLURAL_RE, PLURAL_SUB
end
regex_for_query(query, exhaustive=true) click to toggle source
# File lib/web_utils.rb, line 293
def regex_for_query query, exhaustive=true
  atoms = query.split(QUERY_SPLITTER)
  atom_patterns = atoms.map{|a| "(?=.*\\b#{a})" }
  sep = exhaustive ? EMPTY_STRING : PIPE
  /#{atom_patterns.join(sep)}/i.freeze
end
resolve_class_name(s, context=Kernel) click to toggle source
# File lib/web_utils.rb, line 98
def resolve_class_name s, context=Kernel
  current, *payload = s.to_s.split(CONST_SEP)
  raise(NameError) if current.nil?
  const = context.const_get(current)
  if payload.empty?
    const
  else
    resolve_class_name(payload.join(CONST_SEP),const)
  end
end
resolve_dasherized_class_name(s) click to toggle source
# File lib/web_utils.rb, line 110
def resolve_dasherized_class_name s
  resolve_class_name(undasherize_class_name(s.to_s)) 
end
singularize(s) click to toggle source
# File lib/web_utils.rb, line 71
def singularize s
  if s.end_with? XES_STRING
    s[0..-3]
  elsif s.end_with? IES_STRING
    s.sub(SINGULAR_RE, Y_STRING)
  elsif s.end_with? S_STRING
    s[0..-2]
  else
    s.dup
  end
end
slugify(s, force_lower=true) click to toggle source
# File lib/web_utils.rb, line 161
def slugify s, force_lower=true
  s = s.to_s
    .tr(ACCENTS, WITHOUT_ACCENTS)
    .gsub(AMPERSAND, AND_STRING)
    .gsub(PERCENT, SPACE_PERCENT_STRING)
    .gsub(DASHIFY_RE, DASH)
    .gsub(EDGE_DASH_RE, EMPTY_STRING)
  s = s.downcase if force_lower
  escape(s)
end
truncate(s, c=320, ellipsis=ELLIPSIS) click to toggle source
# File lib/web_utils.rb, line 283
def truncate s, c=320, ellipsis=ELLIPSIS
  s.to_s
    .gsub(TAG_REGEX, EMPTY_STRING)
    .gsub(NL_RE, SPACE)
    .sub(/^(.{#{c}}\w*).*$/m, ARG1_SUB+ellipsis)
end
u(text) click to toggle source
# File lib/web_utils.rb, line 371
def u text
  escape text
end
undasherize_class_name(s) click to toggle source
# File lib/web_utils.rb, line 93
def undasherize_class_name s
  s.capitalize.gsub(DASH_LOWER_OR_NUM_RE) {|str| $1.upcase }.gsub(DASH, CONST_SEP)
end

Private Instance Methods

automatic_html(s, br=BR_TAG) click to toggle source
# File lib/web_utils.rb, line 267
def automatic_html s, br=BR_TAG
  replaced = s.to_s.
  gsub(LINK_REGEX) do |str|
    url = complete_link $1
    "<a href='#{url}' target='_blank'>#{$1}</a>"
  end.
  gsub(EMAIL_REGEX) do |str|
    "<a href='mailto:#{$1.downcase}'>#{$1}</a>"
  end
  nl2br(replaced,br)
end
automatic_typecast(str, casted=TYPECASTABLE) click to toggle source
# File lib/web_utils.rb, line 199
def automatic_typecast str, casted=TYPECASTABLE 
  return str unless str.is_a?(String)
  casted = casted.map do |sym|
    case sym
    when :int
      :integer
    when :bool
      :boolean
    else
      sym
    end
  end
  if casted.include?(:boolean) and str == TRUE_STRING
    true
  elsif casted.include?(:boolean) and str == FALSE_STRING
    false
  elsif casted.include?(:nil) and str == EMPTY_STRING
    nil
  elsif casted.include?(:integer) and str =~ INT_RE
    str.to_i
  elsif casted.include?(:float) and str =~ FLOAT_RE
    str.to_f
  else
    str
  end
end
being_crawled?(request) click to toggle source
# File lib/web_utils.rb, line 361
def being_crawled? request
  request.user_agent =~ BOT_REGEX
end
blank?(s) click to toggle source
# File lib/web_utils.rb, line 47
def blank? s
  return true if s.nil?
  # Not much difference with strip on benchmarks
  # return (s.empty? or BLANK_RE.match?(s)) if s.is_a?(String)
  return (s.strip.empty?) if s.is_a?(String)
  return s.empty? if s.respond_to?(:empty?)
  return true if s==false
  false
end
branded_filename(path, brand=DEFAULT_BRAND) click to toggle source
# File lib/web_utils.rb, line 340
def branded_filename path, brand=DEFAULT_BRAND
  "#{File.dirname(path)}/#{brand}-#{File.basename(path)}"
    .sub(START_DOT_SLASH_RE, EMPTY_STRING)
end
dasherize_class_name(s) click to toggle source
# File lib/web_utils.rb, line 86
def dasherize_class_name s
  s.gsub(UPPER_OR_NUM_RE) {|str| "-#{str.downcase}" }[1..-1].gsub(CONST_SEP, DASH)
end
deep_copy(original) click to toggle source
# File lib/web_utils.rb, line 141
def deep_copy original
  Marshal.load(Marshal.dump(original))
end
display_price(int) click to toggle source
# File lib/web_utils.rb, line 307
def display_price int
  unless int.is_a?(Integer)
    raise(TypeError, PRICE_ERR_MSG)
  end
  (PRICE_FMT % (int/100.0))
    .sub(NO_CENTS_RE, EMPTY_STRING)
    .reverse
    .gsub(THOUSANDS_RE, THOUSANDS_SUB)
    .reverse
end
each_stub(obj, &block) click to toggle source
# File lib/web_utils.rb, line 182
def each_stub obj, &block 
  raise TypeError, EACH_STUB_ERR_MSG unless obj.respond_to?(:each_with_index)
  obj.each_with_index do |(k,v),i|
    value = v || k
    if value.is_a?(Hash) || value.is_a?(Array)
      each_stub(value,&block)
    else
      block.call(obj, (v.nil? ? i : k), value)
    end
  end
end
ensure_key(h, k, v) click to toggle source
# File lib/web_utils.rb, line 151
def ensure_key h, k, v
  {k=>v}.merge h
end
ensure_key!(h, k, v) click to toggle source
# File lib/web_utils.rb, line 146
def ensure_key! h, k, v
  h.fetch(k) {|k| h.store(k, v) }
end
filename_variation(path, variation, ext) click to toggle source
# File lib/web_utils.rb, line 346
def filename_variation path, variation, ext
  old_ext = File.extname(path) 
  path.sub(/#{Regexp.escape old_ext}$/, ".#{variation}.#{ext}")
end
generate_random_id(size=ID_SIZE) click to toggle source
# File lib/web_utils.rb, line 231
def generate_random_id size=ID_SIZE
  warn DEPRECATED_RANDOM_ID_STRING
  id = String.new
  size.times{id << ID_CHARS[rand(ID_CHARS.size)]} 
  id
end
get_value(raw, context=Kernel) click to toggle source
# File lib/web_utils.rb, line 130
def get_value raw, context=Kernel
  if raw.is_a? Proc
    raw.call
  elsif raw.is_a? Symbol
    context.__send__ raw
  else
    raw
  end
end
h(text) click to toggle source
# File lib/web_utils.rb, line 366
def h text
  escape_html text
end
initial_request?(request) click to toggle source
# File lib/web_utils.rb, line 352
def initial_request? request
  URI.parse(request.referer).host!=request.host
rescue URI::InvalidURIError
  return true
end
label_for_field(field_name) click to toggle source
# File lib/web_utils.rb, line 175
def label_for_field field_name
  field_name.to_s.scan(ALPHA_NUM_RE).map(&:capitalize).join(SPACE)
end
nl2br(s, br=BR_TAG) click to toggle source
# File lib/web_utils.rb, line 241
def nl2br s, br=BR_TAG
  s.to_s.gsub(RN_RE, br)
end
parse_price(string) click to toggle source
# File lib/web_utils.rb, line 324
def parse_price string
  unless string.is_a?(String)
    raise(TypeError, PRICE_PARSE_ERR_MSG) 
  end
  string = string.gsub(NON_PRICE_CHARS_RE, EMPTY_STRING)
  if string[COMMA_BASED_PRICE_RE]
    # comma-based price
    string = string.tr(*SWITCH_DOT_COMMA_TR)
  end
  (PRICE_FMT % string.gsub(COMMA, EMPTY_STRING)).gsub(DOT, EMPTY_STRING).to_i
end
pluralize(s) click to toggle source
# File lib/web_utils.rb, line 61
def pluralize s
  s = s.dup
  s<<E_STRING if s[-1,1]==X_STRING
  s<<S_STRING
  s.sub PLURAL_RE, PLURAL_SUB
end
regex_for_query(query, exhaustive=true) click to toggle source
# File lib/web_utils.rb, line 293
def regex_for_query query, exhaustive=true
  atoms = query.split(QUERY_SPLITTER)
  atom_patterns = atoms.map{|a| "(?=.*\\b#{a})" }
  sep = exhaustive ? EMPTY_STRING : PIPE
  /#{atom_patterns.join(sep)}/i.freeze
end
resolve_class_name(s, context=Kernel) click to toggle source
# File lib/web_utils.rb, line 98
def resolve_class_name s, context=Kernel
  current, *payload = s.to_s.split(CONST_SEP)
  raise(NameError) if current.nil?
  const = context.const_get(current)
  if payload.empty?
    const
  else
    resolve_class_name(payload.join(CONST_SEP),const)
  end
end
resolve_dasherized_class_name(s) click to toggle source
# File lib/web_utils.rb, line 110
def resolve_dasherized_class_name s
  resolve_class_name(undasherize_class_name(s.to_s)) 
end
singularize(s) click to toggle source
# File lib/web_utils.rb, line 71
def singularize s
  if s.end_with? XES_STRING
    s[0..-3]
  elsif s.end_with? IES_STRING
    s.sub(SINGULAR_RE, Y_STRING)
  elsif s.end_with? S_STRING
    s[0..-2]
  else
    s.dup
  end
end
slugify(s, force_lower=true) click to toggle source
# File lib/web_utils.rb, line 161
def slugify s, force_lower=true
  s = s.to_s
    .tr(ACCENTS, WITHOUT_ACCENTS)
    .gsub(AMPERSAND, AND_STRING)
    .gsub(PERCENT, SPACE_PERCENT_STRING)
    .gsub(DASHIFY_RE, DASH)
    .gsub(EDGE_DASH_RE, EMPTY_STRING)
  s = s.downcase if force_lower
  escape(s)
end
truncate(s, c=320, ellipsis=ELLIPSIS) click to toggle source
# File lib/web_utils.rb, line 283
def truncate s, c=320, ellipsis=ELLIPSIS
  s.to_s
    .gsub(TAG_REGEX, EMPTY_STRING)
    .gsub(NL_RE, SPACE)
    .sub(/^(.{#{c}}\w*).*$/m, ARG1_SUB+ellipsis)
end
u(text) click to toggle source
# File lib/web_utils.rb, line 371
def u text
  escape text
end
undasherize_class_name(s) click to toggle source
# File lib/web_utils.rb, line 93
def undasherize_class_name s
  s.capitalize.gsub(DASH_LOWER_OR_NUM_RE) {|str| $1.upcase }.gsub(DASH, CONST_SEP)
end