module Tor::Utils

Public Instance Methods

encode_html(body) click to toggle source
# File lib/rest_tor/utils.rb, line 14
def encode_html(body)
  if /<meta .*?content=".*?charset=(\w+)"/ =~ body.encode("UTF-16be", :invalid=>:replace, :replace=>"?").encode('UTF-8')
    encode = $1
    if /utf-8/i !~ encode
      begin
        body = body.dup.force_encoding(encode).encode("utf-8", invalid: :replace, under: :replace) 
      rescue Exception => e
        Tor.logger.info "#{e.class}:#{e.message} (Tor.request)"
      end
    end
  end
  body
end
number_to_human_size(num, options={}) click to toggle source
# File lib/rest_tor/utils.rb, line 10
def number_to_human_size(num, options={})
  ActiveSupport::NumberHelper::NumberToHumanSizeConverter.convert num, options
end
to_json(body) click to toggle source
# File lib/rest_tor/utils.rb, line 3
def to_json(body)
  JSON.parse(body)
rescue Exception => e
  Tor.logger.info "#{e.class}:#{e.message} (Tor.request)"
  {}
end
with_lock(key) { || ... } click to toggle source
# File lib/rest_tor/utils.rb, line 28
def with_lock(key)
  name = "utils:with_lock:#{key}"
  pid = Redis.current.get(name)
  begin
    raise LockedError if pid.blank? or Process.getpgid(pid.to_i)
  rescue Errno::ESRCH, LockedError
    yield if Redis.current.setnx(name, Process.pid)
  end
ensure
  Redis.current.del(name)
end