Module: WebUtils

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

Constant Summary collapse

VERSION =
'0.1.0'
ACCENTS =
"ÀÁÂÃÄÅàáâãäåĀāĂ㥹ÇçĆćĈĉĊċČčÐðĎďĐđÈÉÊËèéêëĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħÌÍÎÏìíîïĨĩĪīĬĭĮįİıĴĵĶķĸĹĺĻļĽľĿŀŁłÑñŃńŅņŇňʼnŊŋÒÓÔÕÖØòóôõöøŌōŎŏŐőŔŕŖŗŘřŚśŜŝŞ"
WITHOUT_ACCENTS =
"AAAAAAaaaaaaAaAaAaCcCcCcCcCcDdDdDdEEEEeeeeEeEeEeEeEeGgGgGgGgHhHhIIIIiiiiIiIiIiIiIiJjKkkLlLlLlLlLlNnNnNnNnnNnOOOOOOooooooOoOoOoRrRrRrSsSsSsSssT"
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



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

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).gsub("@", "&#64;")
end

.automatic_typecast(str, casted = TYPECASTABLE) ⇒ Object



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

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

Returns:

  • (Boolean)


279
280
281
# File 'lib/web_utils.rb', line 279

def being_crawled? request
  request.user_agent =~ BOT_REGEX
end

.blank?(s) ⇒ Boolean

Returns:

  • (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



260
261
262
263
# File 'lib/web_utils.rb', line 260

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


189
190
191
192
193
194
195
# File 'lib/web_utils.rb', line 189

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



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

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)


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

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

Returns:

  • (Boolean)


198
199
200
# File 'lib/web_utils.rb', line 198

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

.filename_variation(path, variation, ext) ⇒ Object



266
267
268
269
# File 'lib/web_utils.rb', line 266

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



176
177
178
179
180
181
# File 'lib/web_utils.rb', line 176

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


294
295
296
# File 'lib/web_utils.rb', line 294

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



284
285
286
# File 'lib/web_utils.rb', line 284

def h text
  escape_html text
end

.initial_request?(request) ⇒ Boolean

Returns:

  • (Boolean)


272
273
274
275
# File 'lib/web_utils.rb', line 272

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



127
128
129
# File 'lib/web_utils.rb', line 127

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

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



184
185
186
# File 'lib/web_utils.rb', line 184

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

.parse_price(string) ⇒ Object



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

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



227
228
229
230
231
232
# File 'lib/web_utils.rb', line 227

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



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

def slugify s, force_lower=true
  s = s.to_s
    .tr(ACCENTS, WITHOUT_ACCENTS)
    .tr(' .,;:?!/\'"()[]{}<>','-')
    .gsub(/&/, 'and')
    .gsub(/-+/,'-')
    .gsub(/(^-|-$)/,'')
  s = s.downcase if force_lower
  escape(s)
end

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



219
220
221
222
223
224
# File 'lib/web_utils.rb', line 219

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

.u(text) ⇒ Object



289
290
291
# File 'lib/web_utils.rb', line 289

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