Module: Tor::Utils

Extended by:
Utils
Included in:
Utils
Defined in:
lib/rest_tor/utils.rb

Instance Method Summary collapse

Instance Method Details

#encode_html(body) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
# 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
        logger.info "#{e.class}:#{e.message}(Tor.request)"
      end
    end
  end
  body
end

#number_to_human_size(num, options = {}) ⇒ Object



10
11
12
# 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) ⇒ Object



3
4
5
6
7
8
# File 'lib/rest_tor/utils.rb', line 3

def to_json(body)
  JSON.parse(body)
rescue Exception => e
  logger.info "#{e.class}:#{e.message}"
  {}
end

#with_lock(key) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
# 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