Module: Sidekiq::WebHelpers

Defined in:
lib/sidekiq/web/helpers.rb

Overview

This is not a public API

Constant Summary collapse

SAFE_QPARAMS =
%w(page poll)
RETRY_JOB_KEYS =
Set.new(%w(
  queue class args retry_count retried_at failed_at
  jid error_message error_class backtrace
  error_backtrace enqueued_at retry wrapped
  created_at
))

Instance Method Summary collapse

Instance Method Details

#add_to_headObject

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

<% add_to_head do %>
  <link rel="stylesheet" .../>
  <meta .../>
<% end %>


51
52
53
54
# File 'lib/sidekiq/web/helpers.rb', line 51

def add_to_head
  @head_html ||= []
  @head_html << yield.dup if block_given?
end

#clear_cachesObject



24
25
26
27
# File 'lib/sidekiq/web/helpers.rb', line 24

def clear_caches
  @@strings = nil
  @@locale_files = nil
end

#csrf_tagObject



179
180
181
# File 'lib/sidekiq/web/helpers.rb', line 179

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

#current_pathObject



137
138
139
# File 'lib/sidekiq/web/helpers.rb', line 137

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

#current_statusObject



141
142
143
# File 'lib/sidekiq/web/helpers.rb', line 141

def current_status
  workers.size == 0 ? 'idle' : 'active'
end

#delete_or_add_queue(job, params) ⇒ Object



270
271
272
273
274
275
276
# File 'lib/sidekiq/web/helpers.rb', line 270

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



173
174
175
176
177
# File 'lib/sidekiq/web/helpers.rb', line 173

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

#display_custom_headObject



56
57
58
# File 'lib/sidekiq/web/helpers.rb', line 56

def display_custom_head
  @head_html.join if defined?(@head_html)
end

#environment_title_prefixObject



243
244
245
246
247
# File 'lib/sidekiq/web/helpers.rb', line 243

def environment_title_prefix
  environment = Sidekiq.options[:environment] || ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'development'

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

#filteringObject

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



40
41
# File 'lib/sidekiq/web/helpers.rb', line 40

def filtering(*)
end

#find_locale_files(lang) ⇒ Object



35
36
37
# File 'lib/sidekiq/web/helpers.rb', line 35

def find_locale_files(lang)
  locale_files.select { |file| file =~ /\/#{lang}\.yml$/ }
end

#get_localeObject



90
91
92
# File 'lib/sidekiq/web/helpers.rb', line 90

def get_locale
  strings(locale)
end

#h(text) ⇒ Object



223
224
225
226
227
228
229
# File 'lib/sidekiq/web/helpers.rb', line 223

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



150
151
152
# File 'lib/sidekiq/web/helpers.rb', line 150

def job_params(job, score)
  "#{score}-#{job['jid']}"
end

#localeObject

Given a browser request Accept-Language header like “fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,ru;q=0.2”, this function will return “fr” since that’s the first code with a matching locale in web/locales



72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/sidekiq/web/helpers.rb', line 72

def locale
  @locale ||= begin
    locale = 'en'.freeze
    languages = env['HTTP_ACCEPT_LANGUAGE'.freeze] || 'en'.freeze
    languages.downcase.split(','.freeze).each do |lang|
      next if lang == '*'.freeze
      lang = lang.split(';'.freeze)[0]
      break locale = lang if find_locale_files(lang).any?
    end
    locale
  end
end

#locale_filesObject



29
30
31
32
33
# File 'lib/sidekiq/web/helpers.rb', line 29

def locale_files
  @@locale_files ||= settings.locales.flat_map do |path|
    Dir["#{path}/*.yml"]
  end
end

#namespaceObject



125
126
127
# File 'lib/sidekiq/web/helpers.rb', line 125

def namespace
  @@ns ||= Sidekiq.redis { |conn| conn.respond_to?(:namespace) ? conn.namespace : nil }
end

#number_with_delimiter(number) ⇒ Object



210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/sidekiq/web/helpers.rb', line 210

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

#parse_params(params) ⇒ Object



154
155
156
157
# File 'lib/sidekiq/web/helpers.rb', line 154

def parse_params(params)
  score, jid = params.split("-")
  [score.to_f, jid]
end

#poll_pathObject



60
61
62
63
64
65
66
# File 'lib/sidekiq/web/helpers.rb', line 60

def poll_path
  if current_path != '' && params['poll']
    root_path + current_path
  else
    ""
  end
end

#processesObject



107
108
109
# File 'lib/sidekiq/web/helpers.rb', line 107

def processes
  @processes ||= Sidekiq::ProcessSet.new
end

#product_versionObject



249
250
251
# File 'lib/sidekiq/web/helpers.rb', line 249

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

#qparams(options) ⇒ Object

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



162
163
164
165
166
167
# File 'lib/sidekiq/web/helpers.rb', line 162

def qparams(options)
  options = options.stringify_keys
  params.merge(options).map do |key, value|
    SAFE_QPARAMS.include?(key) ? "#{key}=#{CGI.escape(value.to_s)}" : next
  end.compact.join("&")
end

#redirect_with_query(url) ⇒ Object

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



233
234
235
236
237
238
239
240
241
# File 'lib/sidekiq/web/helpers.rb', line 233

def redirect_with_query(url)
  r = request.referer
  if r && r =~ /\?/
    ref = URI(r)
    redirect("#{url}?#{ref.query}")
  else
    redirect url
  end
end

#redis_connectionObject



121
122
123
# File 'lib/sidekiq/web/helpers.rb', line 121

def redis_connection
  Sidekiq.redis { |conn| conn.client.id }
end

#redis_connection_and_namespaceObject



253
254
255
256
257
258
# File 'lib/sidekiq/web/helpers.rb', line 253

def redis_connection_and_namespace
  @redis_connection_and_namespace ||= begin
    namespace_suffix = namespace == nil ? '' : "##{namespace}"
    "#{redis_connection}#{namespace_suffix}"
  end
end

#redis_infoObject



129
130
131
# File 'lib/sidekiq/web/helpers.rb', line 129

def redis_info
  Sidekiq.redis_info
end

#relative_time(time) ⇒ Object



145
146
147
148
# File 'lib/sidekiq/web/helpers.rb', line 145

def relative_time(time)
  stamp = time.getutc.iso8601
  %{<time title="#{stamp}" datetime="#{stamp}">#{time}</time>}
end

#retries_with_score(score) ⇒ Object



115
116
117
118
119
# File 'lib/sidekiq/web/helpers.rb', line 115

def retries_with_score(score)
  Sidekiq.redis do |conn|
    conn.zrangebyscore('retry', score, score)
  end.map { |msg| Sidekiq.load_json(msg) }
end

#retry_extra_items(retry_job) ⇒ Object



202
203
204
205
206
207
208
# File 'lib/sidekiq/web/helpers.rb', line 202

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



260
261
262
263
264
265
266
267
268
# File 'lib/sidekiq/web/helpers.rb', line 260

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_pathObject



133
134
135
# File 'lib/sidekiq/web/helpers.rb', line 133

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

#statsObject



111
112
113
# File 'lib/sidekiq/web/helpers.rb', line 111

def stats
  @stats ||= Sidekiq::Stats.new
end

#strings(lang) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/sidekiq/web/helpers.rb', line 10

def strings(lang)
  @@strings ||= {}
  @@strings[lang] ||= begin
    # Allow sidekiq-web extensions to add locale paths
    # so extensions can be localized
    settings.locales.each_with_object({}) do |path, global|
      find_locale_files(lang).each do |file|
        strs = YAML.load(File.open(file))
        global.deep_merge!(strs[lang])
      end
    end
  end
end

#t(msg, options = {}) ⇒ Object



94
95
96
97
98
99
100
101
# File 'lib/sidekiq/web/helpers.rb', line 94

def t(msg, options={})
  string = get_locale[msg] || msg
  if options.empty?
    string
  else
    string % options
  end
end

#to_display(arg) ⇒ Object



183
184
185
186
187
188
189
190
191
192
193
# File 'lib/sidekiq/web/helpers.rb', line 183

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

#truncate(text, truncate_after_chars = 2000) ⇒ Object



169
170
171
# File 'lib/sidekiq/web/helpers.rb', line 169

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

#unfiltered?Boolean

mperham/sidekiq#3243

Returns:

  • (Boolean)


86
87
88
# File 'lib/sidekiq/web/helpers.rb', line 86

def unfiltered?
  yield unless env['PATH_INFO'].start_with?("/filter/")
end

#workersObject



103
104
105
# File 'lib/sidekiq/web/helpers.rb', line 103

def workers
  @workers ||= Sidekiq::Workers.new
end