module Sidekiq::WebHelpers

This is not a public API

Constants

RETRY_JOB_KEYS
SAFE_QPARAMS

Public Instance Methods

add_to_head() { || ... } click to toggle source

This view helper provide ability display you html code in to head of page. Example:

<% add_to_head do %>
  <link rel="stylesheet" .../>
  <meta .../>
<% end %>
# File lib/sidekiq/web/helpers.rb, line 64
def add_to_head
  @head_html ||= []
  @head_html << yield.dup if block_given?
end
available_locales() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 44
def available_locales
  @available_locales ||= locale_files.map { |path| File.basename(path, ".yml") }.uniq
end
clear_caches() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 32
def clear_caches
  @strings = nil
  @locale_files = nil
  @available_locales = nil
end
csrf_tag() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 227
def csrf_tag
  "<input type='hidden' name='authenticity_token' value='#{env[:csrf_token]}'/>"
end
current_path() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 173
def current_path
  @current_path ||= request.path_info.gsub(/^\//, "")
end
current_status() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 177
def current_status
  workers.size == 0 ? "idle" : "active"
end
delete_or_add_queue(job, params) click to toggle source
# File lib/sidekiq/web/helpers.rb, line 334
def delete_or_add_queue(job, params)
  if params["delete"]
    job.delete
  elsif params["add_to_queue"]
    job.add_to_queue
  end
end
display_args(args, truncate_after_chars = 2000) click to toggle source
# File lib/sidekiq/web/helpers.rb, line 214
def display_args(args, truncate_after_chars = 2000)
  return "Invalid job payload, args is nil" if args.nil?
  return "Invalid job payload, args must be an Array, not #{args.class.name}" unless args.is_a?(Array)

  begin
    args.map { |arg|
      h(truncate(to_display(arg), truncate_after_chars))
    }.join(", ")
  rescue
    "Illegal job arguments: #{h args.inspect}"
  end
end
display_custom_head() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 69
def display_custom_head
  @head_html.join if defined?(@head_html)
end
display_tags(job, within = nil) click to toggle source

within is used by Sidekiq Pro

# File lib/sidekiq/web/helpers.rb, line 115
def display_tags(job, within = nil)
  job.tags.map { |tag|
    "<span class='label label-info jobtag'>#{::Rack::Utils.escape_html(tag)}</span>"
  }.join(" ")
end
environment_title_prefix() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 303
def environment_title_prefix
  environment = Sidekiq.options[:environment] || ENV["APP_ENV"] || ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development"

  "[#{environment.upcase}] " unless environment == "production"
end
filtering(*) click to toggle source

This is a hook for a Sidekiq Pro feature. Please don't touch.

# File lib/sidekiq/web/helpers.rb, line 53
def filtering(*)
end
find_locale_files(lang) click to toggle source
# File lib/sidekiq/web/helpers.rb, line 48
def find_locale_files(lang)
  locale_files.select { |file| file =~ /\/#{lang}\.yml$/ }
end
format_memory(rss_kb) click to toggle source
# File lib/sidekiq/web/helpers.rb, line 256
def format_memory(rss_kb)
  return "0" if rss_kb.nil? || rss_kb == 0

  if rss_kb < 100_000
    "#{number_with_delimiter(rss_kb)} KB"
  elsif rss_kb < 10_000_000
    "#{number_with_delimiter((rss_kb / 1024.0).to_i)} MB"
  else
    "#{number_with_delimiter((rss_kb / (1024.0 * 1024.0)).round(1))} GB"
  end
end
get_locale() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 126
def get_locale
  strings(locale)
end
h(text) click to toggle source
# File lib/sidekiq/web/helpers.rb, line 283
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
job_params(job, score) click to toggle source
# File lib/sidekiq/web/helpers.rb, line 186
def job_params(job, score)
  "#{score}-#{job["jid"]}"
end
locale() click to toggle source

Given an Accept-Language header like “fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,ru;q=0.2” this method will try to best match the available locales to the user's preferred languages.

Inspiration taken from github.com/iain/http_accept_language/blob/master/lib/http_accept_language/parser.rb

# File lib/sidekiq/web/helpers.rb, line 98
def locale
  @locale ||= begin
    matched_locale = user_preferred_languages.map { |preferred|
      preferred_language = preferred.split("-", 2).first

      lang_group = available_locales.select { |available|
        preferred_language == available.split("-", 2).first
      }

      lang_group.find { |lang| lang == preferred } || lang_group.min_by(&:length)
    }.compact.first

    matched_locale || "en"
  end
end
locale_files() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 38
def locale_files
  @locale_files ||= settings.locales.flat_map { |path|
    Dir["#{path}/*.yml"]
  }
end
namespace() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 161
def namespace
  @ns ||= Sidekiq.redis { |conn| conn.respond_to?(:namespace) ? conn.namespace : nil }
end
number_with_delimiter(number) click to toggle source
# File lib/sidekiq/web/helpers.rb, line 268
def number_with_delimiter(number)
  return "" if number.nil?

  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
parse_params(params) click to toggle source
# File lib/sidekiq/web/helpers.rb, line 190
def parse_params(params)
  score, jid = params.split("-", 2)
  [score.to_f, jid]
end
processes() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 147
def processes
  @processes ||= Sidekiq::ProcessSet.new
end
product_version() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 309
def product_version
  "Sidekiq v#{Sidekiq::VERSION}"
end
qparams(options) click to toggle source

Merge options with current params, filter safe params, and stringify to query string

# File lib/sidekiq/web/helpers.rb, line 198
def qparams(options)
  stringified_options = options.transform_keys(&:to_s)

  to_query_string(params.merge(stringified_options))
end
redirect_with_query(url) click to toggle source

Any paginated list that performs an action needs to redirect back to the proper page after performing that action.

# File lib/sidekiq/web/helpers.rb, line 293
def redirect_with_query(url)
  r = request.referer
  if r && r =~ /\?/
    ref = URI(r)
    redirect("#{url}?#{ref.query}")
  else
    redirect url
  end
end
redis_connection() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 155
def redis_connection
  Sidekiq.redis do |conn|
    conn.connection[:id]
  end
end
redis_connection_and_namespace() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 317
def redis_connection_and_namespace
  @redis_connection_and_namespace ||= begin
    namespace_suffix = namespace.nil? ? "" : "##{namespace}"
    "#{redis_connection}#{namespace_suffix}"
  end
end
redis_info() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 165
def redis_info
  Sidekiq.redis_info
end
relative_time(time) click to toggle source
# File lib/sidekiq/web/helpers.rb, line 181
def relative_time(time)
  stamp = time.getutc.iso8601
  %(<time class="ltr" dir="ltr" title="#{stamp}" datetime="#{stamp}">#{time}</time>)
end
retry_extra_items(retry_job) click to toggle source
# File lib/sidekiq/web/helpers.rb, line 248
def retry_extra_items(retry_job)
  @retry_extra_items ||= {}.tap do |extra|
    retry_job.item.each do |key, value|
      extra[key] = value unless RETRY_JOB_KEYS.include?(key)
    end
  end
end
retry_or_delete_or_kill(job, params) click to toggle source
# File lib/sidekiq/web/helpers.rb, line 324
def retry_or_delete_or_kill(job, params)
  if params["retry"]
    job.retry
  elsif params["delete"]
    job.delete
  elsif params["kill"]
    job.kill
  end
end
root_path() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 169
def root_path
  "#{env["SCRIPT_NAME"]}/"
end
rtl?() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 77
def rtl?
  text_direction == "rtl"
end
server_utc_time() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 313
def server_utc_time
  Time.now.utc.strftime("%H:%M:%S UTC")
end
singularize(str, count) click to toggle source
# File lib/sidekiq/web/helpers.rb, line 24
def singularize(str, count)
  if count == 1 && str.respond_to?(:singularize) # rails
    str.singularize
  else
    str
  end
end
sort_direction_label() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 139
def sort_direction_label
  params[:direction] == "asc" ? "&uarr;" : "&darr;"
end
stats() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 151
def stats
  @stats ||= Sidekiq::Stats.new
end
strings(lang) click to toggle source
# File lib/sidekiq/web/helpers.rb, line 11
def strings(lang)
  @strings ||= {}

  # Allow sidekiq-web extensions to add locale paths
  # so extensions can be localized
  @strings[lang] ||= settings.locales.each_with_object({}) do |path, global|
    find_locale_files(lang).each do |file|
      strs = YAML.load(File.open(file))
      global.merge!(strs[lang])
    end
  end
end
t(msg, options = {}) click to toggle source
# File lib/sidekiq/web/helpers.rb, line 130
def t(msg, options = {})
  string = get_locale[msg] || strings("en")[msg] || msg
  if options.empty?
    string
  else
    string % options
  end
end
text_direction() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 73
def text_direction
  get_locale["TextDirection"] || "ltr"
end
to_display(arg) click to toggle source
# File lib/sidekiq/web/helpers.rb, line 231
def to_display(arg)
  arg.inspect
rescue
  begin
    arg.to_s
  rescue => ex
    "Cannot display argument: [#{ex.class.name}] #{ex.message}"
  end
end
to_query_string(params) click to toggle source
# File lib/sidekiq/web/helpers.rb, line 204
def to_query_string(params)
  params.map { |key, value|
    SAFE_QPARAMS.include?(key) ? "#{key}=#{CGI.escape(value.to_s)}" : next
  }.compact.join("&")
end
truncate(text, truncate_after_chars = 2000) click to toggle source
# File lib/sidekiq/web/helpers.rb, line 210
def truncate(text, truncate_after_chars = 2000)
  truncate_after_chars && text.size > truncate_after_chars ? "#{text[0..truncate_after_chars]}..." : text
end
unfiltered?() { || ... } click to toggle source

mperham/sidekiq#3243

# File lib/sidekiq/web/helpers.rb, line 122
def unfiltered?
  yield unless env["PATH_INFO"].start_with?("/filter/")
end
user_preferred_languages() click to toggle source

See www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

# File lib/sidekiq/web/helpers.rb, line 82
def user_preferred_languages
  languages = env["HTTP_ACCEPT_LANGUAGE"]
  languages.to_s.downcase.gsub(/\s+/, "").split(",").map { |language|
    locale, quality = language.split(";q=", 2)
    locale = nil if locale == "*" # Ignore wildcards
    quality = quality ? quality.to_f : 1.0
    [locale, quality]
  }.sort { |(_, left), (_, right)|
    right <=> left
  }.map(&:first).compact
end
workers() click to toggle source
# File lib/sidekiq/web/helpers.rb, line 143
def workers
  @workers ||= Sidekiq::Workers.new
end