Module: WebUtils

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

Constant Summary collapse

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

Class Method Summary collapse

Class Method Details

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



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

def automatic_html s, br='<br>'
  replaced = s.to_s.
  gsub(/\b((https?:\/\/|ftps?:\/\/|www\.)([A-Za-z0-9\-_=%&@\?\.\/]+))\b/) do |str|
    url = complete_link $1
    "<a href='#{url}' target='_blank'>#{$1}</a>"
  end.
  gsub(/([^\s]+@[^\s]*[a-zA-Z])/) do |str|
    "<a href='mailto:#{$1.downcase}'>#{$1}</a>"
  end
  nl2br(replaced,br).gsub("@", "&#64;")
end

.automatic_typecast(str, casted = [:bool,:nil,:int,:float]) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/web_utils.rb', line 138

def automatic_typecast str, casted=[:bool,:nil,:int,:float] 
  return str unless str.is_a?(String)
  if casted.include?(:bool) and str=='true'
    true
  elsif casted.include?(:bool) and str=='false'
    false
  elsif casted.include?(:nil) and str==''
    nil
  elsif casted.include?(:int) and str=~/^-?\d+$/
    str.to_i
  elsif casted.include?(:float) and str=~/^-?\d*\.\d+$/
    str.to_f
  else
    str
  end
end

.blank?(s) ⇒ Boolean

Returns:

  • (Boolean)


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

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

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



214
215
216
# File 'lib/web_utils.rb', line 214

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


170
171
172
173
174
175
176
# File 'lib/web_utils.rb', line 170

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

.dasherize_class_name(s) ⇒ Object



41
42
43
# File 'lib/web_utils.rb', line 41

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

.deep_copy(original) ⇒ Object



91
92
93
# File 'lib/web_utils.rb', line 91

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

.display_price(int) ⇒ Object

Raises:

  • (TypeError)


202
203
204
205
# File 'lib/web_utils.rb', line 202

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

.each_stub(obj, &block) ⇒ Object

Raises:

  • (TypeError)


125
126
127
128
129
130
131
132
133
134
135
# File 'lib/web_utils.rb', line 125

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



102
103
104
105
106
# File 'lib/web_utils.rb', line 102

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



96
97
98
99
# File 'lib/web_utils.rb', line 96

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

.external_link?(link) ⇒ Boolean

Returns:

  • (Boolean)


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

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

.filename_variation(path, variation, ext) ⇒ Object



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

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



158
159
160
161
162
# File 'lib/web_utils.rb', line 158

def generate_random_id size=ID_SIZE
  id = ''
  size.times{id << ID_CHARS[rand(ID_CHARS.size)]} 
  id
end

.get_value(raw, context = Kernel) ⇒ Object



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

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


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

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

.initial_request?(request) ⇒ Boolean

Returns:

  • (Boolean)


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

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



120
121
122
# File 'lib/web_utils.rb', line 120

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

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



165
166
167
# File 'lib/web_utils.rb', line 165

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

.parse_price(string) ⇒ Object

Raises:

  • (TypeError)


208
209
210
211
# File 'lib/web_utils.rb', line 208

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

.pluralize(s) ⇒ Object



20
21
22
23
24
# File 'lib/web_utils.rb', line 20

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

.resolve_class_name(s, context = Kernel) ⇒ Object

Raises:

  • (NameError)


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

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



63
64
65
# File 'lib/web_utils.rb', line 63

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

.singularize(s) ⇒ Object



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

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
# File 'lib/web_utils.rb', line 113

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

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



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

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

.undasherize_class_name(s) ⇒ Object



46
47
48
# File 'lib/web_utils.rb', line 46

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