Created
March 27, 2012 10:36
-
-
Save wyldrodney/2214710 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module PageStatus | |
require 'net/http' | |
require 'net/https' | |
require 'net/ping/tcp' | |
require 'rchardet19' | |
require 'digest/sha2' | |
class PageProbe | |
def initialize(address) | |
@address = address | |
get_status | |
end | |
attr_reader :time, :code, :message, :body | |
def alive? | |
@alive | |
end | |
private | |
def get_status | |
@uri = URI(@address) | |
if @uri | |
http = Net::HTTP.new(@uri.host, @uri.port) | |
http.use_ssl = true if @uri.scheme == 'https' | |
begin | |
start_point = Time.now.to_f | |
response = http.get(@uri.path, {"User-Agent" => "Mozilla/5.0 (compatible; SiteSaver/0.1; +http://sitesaver.ru/)"}) | |
time_delta = (Time.now.to_f - start_point).round(3) | |
set_answer(response, time_delta) | |
rescue | |
ping(@uri.host) | |
end | |
end | |
end | |
def ping(address) | |
Net::Ping::TCP.service_check = true | |
set_answer(Net::Ping::TCP.new(address).ping?) | |
end | |
def set_answer(response, time_delta=nil) | |
@code = nil | |
@message = nil | |
@time = time_delta | |
@body = nil | |
case | |
when response.kind_of?(TrueClass) | |
@alive = true | |
when response.kind_of?(FalseClass) | |
@alive = false | |
else | |
@alive = true | |
@code = response.code | |
@message = response.message | |
@body = response.body | |
end | |
end | |
end | |
class PageAnalyze | |
def initialize(page) | |
@page = page | |
if @page.body | |
convert_to_utf8 | |
add_line_breaks | |
else | |
@body = nil | |
end | |
end | |
def body | |
@body | |
end | |
def checksum | |
@body ? Digest::SHA256.hexdigest(@body) : nil | |
end | |
private | |
def convert_to_utf8 | |
begin | |
charset = CharDet.detect(@page.body, silent: false).encoding | |
@body = @page.body.encode('utf-8', charset) | |
rescue | |
@body = nil | |
end | |
end | |
def add_line_breaks | |
buf = '' | |
@body.each_line do |line| | |
line.gsub!(/(?<line><[a-zA-Z]+)/, "\n" + '\k<line>') | |
line.gsub!(/(?<line><\/[a-zA-Z]*>)/, "\n" + '\k<line>') | |
line.gsub!(/(?<line>.{90,120}(>|\s|\t))/, '\k<line>' + "\n") | |
line.gsub!(/\n{2,}/, "\n") | |
line.gsub!(/^\s*/, "") | |
buf << line | |
end | |
@body = buf | |
end | |
end | |
end |
Читаемость ухудшится.
2012/3/27 Mikhail Bortnyk
reply@reply.github.com:
… ``` ruby
http.use_ssl = true if @uri.scheme == 'https'
```
нафига? можно ведь просто
``` ruby
http.use_ssl = @uri.scheme == 'https'
```
---
Reply to this email directly or view it on GitHub:
https://gist.github.com/2214710
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
так разве не лучше? (#33)