Module: Zhong::WebHelpers

Defined in:
lib/zhong/web_helpers.rb

Instance Method Summary collapse

Instance Method Details

#capture(&block) ⇒ Object

Simple capture method for erb templates. The origin was capture method from sinatra-contrib library.



8
9
10
11
# File 'lib/zhong/web_helpers.rb', line 8

def capture(&block)
  block.call
  eval("", block.binding)
end

#csrf_tagObject



39
40
41
# File 'lib/zhong/web_helpers.rb', line 39

def csrf_tag
  "<input type='hidden' name='authenticity_token' value='#{session[:csrf]}'/>"
end

#current_pathObject



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

def current_path
  @current_path ||= request.path_info.gsub(%r(^\/),"")
end

#display_args(args, truncate_after_chars = 2000) ⇒ Object



33
34
35
36
37
# File 'lib/zhong/web_helpers.rb', line 33

def display_args(args, truncate_after_chars = 2000)
  args.map do |arg|
    h(truncate(to_display(arg), truncate_after_chars))
  end.join(", ")
end

#environment_title_prefixObject



74
75
76
77
78
# File 'lib/zhong/web_helpers.rb', line 74

def environment_title_prefix
  environment = ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development"

  "[#{environment.upcase}] " unless environment == "production"
end

#h(text) ⇒ Object



66
67
68
69
70
71
72
# File 'lib/zhong/web_helpers.rb', line 66

def h(text)
  ::Rack::Utils.escape_html(text)
rescue ArgumentError => e
  raise unless e.message.eql?("invalid byte sequence in UTF-8")
  text.encode!("UTF-16", "UTF-8", invalid: :replace, replace: "").encode!("UTF-8", "UTF-16")
  retry
end

#number_with_delimiter(number) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/zhong/web_helpers.rb', line 53

def number_with_delimiter(number)
  begin
    Float(number)
  rescue ArgumentError, TypeError
    return number
  end

  options = {delimiter: ",", separator: "."}
  parts = number.to_s.to_str.split(".")
  parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{options[:delimiter]}")
  parts.join(options[:separator])
end

#product_versionObject



80
81
82
# File 'lib/zhong/web_helpers.rb', line 80

def product_version
  "Zhong v#{Zhong::VERSION}"
end

#relative_time(time) ⇒ Object



21
22
23
24
25
26
27
# File 'lib/zhong/web_helpers.rb', line 21

def relative_time(time)
  if time
    %(<time datetime="#{time.getutc.iso8601}">#{time}</time>)
  else
    "never"
  end
end

#root_pathObject



13
14
15
# File 'lib/zhong/web_helpers.rb', line 13

def root_path
  "#{env['SCRIPT_NAME']}/"
end

#to_display(arg) ⇒ Object



43
44
45
46
47
48
49
50
51
# File 'lib/zhong/web_helpers.rb', line 43

def to_display(arg)
  arg.inspect
rescue
  begin
    arg.to_s
  rescue => ex
    "Cannot display argument: [#{ex.class.name}] #{ex.message}"
  end
end

#truncate(text, truncate_after_chars = 2000) ⇒ Object



29
30
31
# File 'lib/zhong/web_helpers.rb', line 29

def truncate(text, truncate_after_chars = 2000)
  truncate_after_chars && text.size > truncate_after_chars ? "#{text[0..truncate_after_chars]}..." : text
end