Module: WebUtils

Extended by:
Rack::Utils
Defined in:
lib/web_utils.rb

Constant Summary collapse

VERSION =
'0.1.4'
ACCENTS =
"ÀÁÂÃÄÅàáâãäåĀāĂ㥹ÇçĆćĈĉĊċČčÐðĎďĐđÈÉÊËèéêëĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħÌÍÎÏìíîïĨĩĪīĬĭĮįİıĴĵĶķĸĹĺĻļĽľĿŀŁłÑñŃńŅņŇňʼnŊŋÒÓÔÕÖØòóôõöøŌōŎŏŐőŔŕŖŗŘřŚśŜŝŞşŠšſŢţŤťŦŧÙÚÛÜùúûüŨũŪūŬŭŮůŰűŲųŴŵÝýÿŶŷŸŹźŻżŽž"
WITHOUT_ACCENTS =
"AAAAAAaaaaaaAaAaAaCcCcCcCcCcDdDdDdEEEEeeeeEeEeEeEeEeGgGgGgGgHhHhIIIIiiiiIiIiIiIiIiJjKkkLlLlLlLlLlNnNnNnNnnNnOOOOOOooooooOoOoOoRrRrRrSsSsSsSssTtTtTtUUUUuuuuUuUuUuUuUuUuWwYyyYyYZzZzZz"
TYPECASTABLE =
[:bool, :boolean, :nil, :int, :integer, :float]
ID_CHARS =
('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
ID_SIZE =
16
EMAIL_REGEX =
/([^\s]+@[^\s]*[a-zA-Z])/
/\b((https?:\/\/|ftps?:\/\/|www\.)([A-Za-z0-9\-_=%&@\?\.\/]+))\b/
TAG_REGEX =
/<[^>]*>/
BOT_REGEX =
/bot|crawl|slurp|spider/i

Class Method Summary collapse

Class Method Details

.automatic_html(s, br = '<br>') ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
# File 'lib/web_utils.rb', line 203

def automatic_html s, br='<br>'
  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) ⇒ Object



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/web_utils.rb', line 144

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'
    true
  elsif casted.include?(:boolean) and str=='false'
    false
  elsif casted.include?(:nil) and str==''
    nil
  elsif casted.include?(:integer) and str=~/^-?\d+$/
    str.to_i
  elsif casted.include?(:float) and str=~/^-?\d*\.\d+$/
    str.to_f
  else
    str
  end
end

.being_crawled?(request) ⇒ Boolean



277
278
279
# File 'lib/web_utils.rb', line 277

def being_crawled? request
  request.user_agent =~ BOT_REGEX
end

.blank?(s) ⇒ Boolean



17
18
19
# File 'lib/web_utils.rb', line 17

def blank? s
  s.to_s.strip==''
end

.branded_filename(path, brand = 'WebUtils') ⇒ Object



258
259
260
261
# File 'lib/web_utils.rb', line 258

def branded_filename path, brand='WebUtils'
  "#{File.dirname(path)}/#{brand}-#{File.basename(path)}"
    .sub(/^\.\//,'')
end


187
188
189
190
191
192
193
# File 'lib/web_utils.rb', line 187

def complete_link link
  if blank?(link) or link=~/^(\/|[a-z]*:)/
    link
  else
    "//#{link}"
  end
end

.dasherize_class_name(s) ⇒ Object



43
44
45
# File 'lib/web_utils.rb', line 43

def dasherize_class_name s
  s.gsub(/([A-Z]|\d+)/){|str|"-#{str.downcase}"}[1..-1].gsub('::','-')
end

.deep_copy(original) ⇒ Object



93
94
95
# File 'lib/web_utils.rb', line 93

def deep_copy original
  Marshal.load(Marshal.dump(original))
end

.display_price(int) ⇒ Object



233
234
235
236
237
238
239
240
241
242
# File 'lib/web_utils.rb', line 233

def display_price int
  unless int.is_a?(Integer)
    raise(TypeError, 'The price needs to be the price in cents/pence as an integer') 
  end
  ("%.2f" % (int/100.0))
    .sub(/\.00/, '')
    .reverse
    .gsub(/(\d{3})(?=\d)/, '\\1,')
    .reverse
end

.each_stub(obj, &block) ⇒ Object

Raises:

  • (TypeError)


130
131
132
133
134
135
136
137
138
139
140
# File 'lib/web_utils.rb', line 130

def each_stub obj, &block 
  raise TypeError, 'WebUtils.each_stub expects an object which respond to each_with_index' 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) ⇒ Object



104
105
106
107
108
# File 'lib/web_utils.rb', line 104

def ensure_key h, k, v
  new_h = h.dup
  self.ensure_key! new_h, k, v
  new_h
end

.ensure_key!(h, k, v) ⇒ Object



98
99
100
101
# File 'lib/web_utils.rb', line 98

def ensure_key! h, k, v
  h[k] = v unless h.key?(k)
  h[k]
end

.external_link?(link) ⇒ Boolean



196
197
198
# File 'lib/web_utils.rb', line 196

def external_link? link
  !!(link =~ /^[a-z]*:?\/\//)
end

.filename_variation(path, variation, ext) ⇒ Object



264
265
266
267
# File 'lib/web_utils.rb', line 264

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) ⇒ Object



174
175
176
177
178
179
# File 'lib/web_utils.rb', line 174

def generate_random_id size=ID_SIZE
  warn "WebUtils::generate_random_id is deprecated. Use standard SecureRandom instead."
  id = ''
  size.times{id << ID_CHARS[rand(ID_CHARS.size)]} 
  id
end

.get_value(raw, context = Kernel) ⇒ Object



82
83
84
85
86
87
88
89
90
# File 'lib/web_utils.rb', line 82

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


292
293
294
# File 'lib/web_utils.rb', line 292

def google_maps_link address
  "https://www.google.com/maps/search/?api=1&query=#{u address}"
end


70
71
72
73
74
75
76
77
78
79
# File 'lib/web_utils.rb', line 70

def guess_related_class_name context, clue
  context.respond_to?(:name) ? context.name : context.to_s
  clue = clue.to_s
  return clue if clue=~/^[A-Z]/
  if clue=~/^[a-z]/
    clue = undasherize_class_name singularize(clue).gsub('_','-')
    clue = "::#{clue}"
  end
  "#{context}#{clue}"
end

.h(text) ⇒ Object



282
283
284
# File 'lib/web_utils.rb', line 282

def h text
  escape_html text
end

.initial_request?(request) ⇒ Boolean



270
271
272
273
# File 'lib/web_utils.rb', line 270

def initial_request? request
  return true unless request.referer=~URI.regexp
  URI.parse(request.referer).host!=request.host
end

.label_for_field(field_name) ⇒ Object



125
126
127
# File 'lib/web_utils.rb', line 125

def label_for_field field_name
  field_name.to_s.scan(/[a-zA-Z0-9]+/).map(&:capitalize).join(' ')
end

.nl2br(s, br = '<br>') ⇒ Object



182
183
184
# File 'lib/web_utils.rb', line 182

def nl2br s, br='<br>'
  s.to_s.gsub(/\r?\n/,br)
end

.parse_price(string) ⇒ Object



245
246
247
248
249
250
251
252
253
254
255
# File 'lib/web_utils.rb', line 245

def parse_price string
  unless string.is_a?(String)
    raise(TypeError, 'The price needs to be parsed from a String') 
  end
  string = string.gsub(/[^\d\.\-,]/, '')
  if string[/\.\d\d\d$/] or string[/,\d\d?$/]
    # comma-based price 
    string = string.tr '.,', ',.'
  end
  ("%.2f" % string.gsub(/,/, '')).gsub(/\./,'').to_i
end

.pluralize(s) ⇒ Object



22
23
24
25
26
# File 'lib/web_utils.rb', line 22

def pluralize s
  s<<'e' if s[-1,1]=='x'
  s<<'s'
  s.sub(/([b-df-hj-np-tv-z])ys$/,'\1ies')
end

.regex_for_query(query, exhaustive = true) ⇒ Object



225
226
227
228
229
230
# File 'lib/web_utils.rb', line 225

def regex_for_query query, exhaustive=true
  atoms = query.split(/[^a-zA-Z0-9\&]+/)
  atom_patterns = atoms.map{|a| "(?=.*\\b#{a})" }
  sep = exhaustive ? '' : '|'
  regex = /#{atom_patterns.join(sep)}/i
end

.resolve_class_name(s, context = Kernel) ⇒ Object

Raises:

  • (NameError)


53
54
55
56
57
58
59
60
61
62
# File 'lib/web_utils.rb', line 53

def resolve_class_name s, context=Kernel
  current, *payload = s.to_s.split('::')
  raise(NameError) if current.nil?
  const = context.const_get(current)
  if payload.empty?
    const
  else
    resolve_class_name(payload.join('::'),const)
  end
end

.resolve_dasherized_class_name(s) ⇒ Object



65
66
67
# File 'lib/web_utils.rb', line 65

def resolve_dasherized_class_name s
  resolve_class_name(undasherize_class_name(s.to_s)) 
end

.singularize(s) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/web_utils.rb', line 29

def singularize s
  case s
  when /xes$/
    s[0..-3]
  when /ies$/
    s.sub(/ies$/, 'y')
  when /s$/
    s[0..-2]
  else
    s
  end
end

.slugify(s, force_lower = true) ⇒ Object



113
114
115
116
117
118
119
120
121
122
# File 'lib/web_utils.rb', line 113

def slugify s, force_lower=true
  s = s.to_s
    .tr(ACCENTS, WITHOUT_ACCENTS)
    .gsub(/&/, 'and')
    .gsub(/%/, ' percent')
    .gsub(/(\-|[^0-9a-zA-Z])+/,'-')
    .gsub(/(^-|-$)/,'')
  s = s.downcase if force_lower
  escape(s)
end

.truncate(s, c = 320, ellipsis = '...') ⇒ Object



217
218
219
220
221
222
# File 'lib/web_utils.rb', line 217

def truncate s,c=320,ellipsis='...'
  s.to_s
    .gsub(TAG_REGEX, '')
    .gsub(/\n/, ' ')
    .sub(/^(.{#{c}}\w*).*$/m, '\1'+ellipsis)
end

.u(text) ⇒ Object



287
288
289
# File 'lib/web_utils.rb', line 287

def u text
  escape text
end

.undasherize_class_name(s) ⇒ Object



48
49
50
# File 'lib/web_utils.rb', line 48

def undasherize_class_name s
  s.capitalize.gsub(/\-([a-z0-9])/){|str|$1.upcase}.gsub('-','::')
end