fangtingting
12/14/2017 - 1:45 AM

ruby标准库及扩展库的使用

ruby标准库及扩展库的使用

Ruby编码处理

1、Ruby标准库中包含iconv库,提供了编码相互转换的功能。

Iconv.new(to,from)
"//IGNORE":让转换器忽视无效的字节
"//TRANSLIT":让转换器在遇到无法表示的编码时使用相近的字符代替
convert=Iconv.new('UTF-8//IGNORE','GB2312')
str_uft8=convert.iconv(str_gb)


#抓取网页并把网页编码统一转换成UTF-8格式
require 'net/http'
require 'iconv'

def get_webpage(url)
    res=Net::HTTP.get(URI.parse(url))

    #获取网页编码类型
    if res=~ /charset=([^\s'"]+)/i
        encoding = $1
    else
        encoding = 'ISO-8895-1'
    end
        
    convert=Iconv.new('UTF-8//IGNORE',encoding)
    return convert.iconv(res)
end

Ruby操作XML

Ruby标准库中的REXML库来操作XML。

1、创建XML文档

require "rexml/document"

#创建xml文档
doc=REXML::Document.new

#为xml文档添加一个节点
element=doc.add_element('book',{'name' => 'test1','author' => 'test2'})
chapter1=element.add_element('chapter',{'title' => 'chapter 1'})
chapter2=element.add_element('chapter',{'title' => 'chapter 2'})

#为节点添加包含内容
chapter1.add_text "chapter 1 content"
chapter2.add_text "chapter 2 content"

#输出xml
doc.write

2、解析xml

require "rexml/document"
    
xml_doc=File.open(...)
    
doc=REXML::Document.new(xml_doc)

puts doc.root.name
puts doc.root.attributes["name"]

chapter1=doc.root.elements[1]
puts chapter1.attributes['title']
puts chapter1.text

3、访问RSS聚合

RSS(聚合内容):是一种描述和同步网站内容的格式,是目前广泛使用的XML应用。Ruby中提供了一个标准RSS库,可以方便处理RSS文件。

require "rss"
require "open-uri"
require "iconv"

url=".../ddt.xml"
#xml编码都是基于utf8,但是在终端输出rss要转换成gb2312格式
convert=Iconv.new("GB2312","UTF-8")

File.open(url) do |http|
    rss_content=http.read
    #解析rss内容
    rss=RSS::Parser.parse(rss_content,rss)
        
    puts "RSS标题:#{convert.iconv(rss.channel.title).strip}"

    rss.items.each_with_index do |item,i|
        puts "新闻#{i+1}:#{convert.iconv(item.title).strip}"
    end
end

Ruby操作YAML

1、Ruby应用中大量使用YAML格式保存配置文件。几乎所有的Ruby对象都可以用 to_yaml方法转换成YAML格式。YAML在Ruby标准库里。

2、YAML类常用方法

YAML.dump(obj):将obj转成YAML格式

YAML.load(str):解析YAML格式字符串,还原为Ruby对象

YAML.load_file(filename):读取YAML文件,还原为Ruy对象

Ruby操作PDF

Ruby对PDF操作的支持库有很多,例如PDF::HTMLDOC、PDF::WRITE、Ruby FPDF.需要安装扩展库来支持Ruby操作PDF。

Ruby操作ZIP文件

安装rubyzip扩展库,详细文档可在github上搜索查看

gem install rubyzip

Ruby图像处理

Ruby对图像处理需要使用RMagick扩展库来操作图像。RMagick库是ImageMagick(和GraphicsMagick)图像处理库的Ruby绑定,也就是RMagick为Ruby程序提供使用ImageMagick(和GraphicsMagick)的接口,可以让Ruby程序使用它们的图像处理功能。

RMagick的安装和使用方法可以在github上搜索查看。

1、获取图片信息

require "rmagick"
    
file_name=".../test.jpg"
img=RMagick::Image::read(file_name).first

puts "图片格式:#{img.format}"
puts "尺寸:#{img.columns}px*#{img.rows}px"
puts "文件大小:#{img.filesize}"

2、生成缩略图

#创建图像操作对象
img=RMagick::ImageList::new(file_name)

old_width=img.columns
old_height=img.rows

#如果图像宽和高比例不对,则进行裁剪再缩放
if old_with!=old_height
    new_width=[old_width,old_height].min
    #对图像裁剪
    img.crop!(0,0,new_width,new_width)
end
    
#对图像进行缩放
new_img=img.thumbnail(80,80)
    
#保存缩略图
new_img.write("logo.jpg")

3、在图片上添加文字

#添加水印
def add_water_mark(img,text)
    
    text_draw=RMagick::Draw.new
    text_draw.annotate(img,0,0,0,0,text) do
        self.gravity=RMagick::SouthEastGravity  #设置文字在东南角
        self.pointsize=24  #设置文字大小
        self.stroke='black'  #设置文字边沿黑色
        self.fill='#FFFFFF'  #设置文字颜色白色
        self.font_weight=RMagick::BoldWeight  #设置文字粗体
    end
    return img
end

def validate_code(text)

    #生成netscape样式的背景
    bg=RMagick::ImageList.new('newscape:')
        
    #定义一个画布
    canvas=RMagick::ImageList.new
    #将背景放画布上
    canvas.new_image(90,30,RMagick::TextureFill.new(bg))

    #把字符放在画布上
    text_draw=RMagick::Draw.new
    text_draw.annotate(canvas,0,0,0,0,text) do
        self.font_family='Courier New'  #设置文字字体
        self.gravity=RMagick::CenterGravity  #设置文字位置
        self.pointsize=20  #设置文字大小
        self.rotation=rand(15)  #设置文字旋转角度
        self.stroke='black'     #设置文字边沿黑色
        self.fill='#FFFFFF'   #设置文字颜色白色
        self.font_weight=RMagick::BoldWeigh  #设置文字粗体
    end
    return canvas
end

img=RMagick::ImageList::new(file_name)
    
#添加水印
new_img=add_water_mark(img,"文字")
    
#保存缩略图
new_img.write("test.jpg")

#生成随机验证码
codes=('A'..'Z').to_a+('a'..'z').to_a
text=(1..6).inject(""){|s,i| s+codes[rand(codes.size)].to_s}

#生成验证码图片保存
validate_code(text).write('code.gif')

Ruby操作mysql数据库

1、安装扩展库:Ruby/Mysql的接口库。详细API可以网上搜索。

2、连接Mysql数据库

require 'mysql'

begin
    #尝试连接mysql数据库
    my=Mysql.connect('localhost','root','123456','database_name')
        
    #使用sql查询数据库
    res=my.query(sql)
    res.each_hash do |f|
        puts "#{f.id}"
    end
rescue Mysql::Error => err
    puts err.errno
    puts err.error
ensure
    my.close if my
end

Ruby操作Oracle数据库

1、安装扩展库:Ruby/OCI8,具体API可网上搜索

2、连接Oracle数据库

require 'oci8'

ora=OCI8.new('root','123456','database_name')

#读取数据库
ora.exec(sql) do |id|
    puts id
end

通用数据库接口库DBI

1、安装Ruby DBI扩展库,在命令行输入命令安装各种常用数据库的驱动,具体API网上搜索

ruby setup.rb config --with=dbi,dbd_ado,dbd_mysql,dbd_oracle
ruby setup.rb setup
ruby setup.rb install

2、使用DBI访问Mysql、Oracle

require 'dbi'
DBI.connect('DBI:Mysql:database:host','root','123456') do |dbh|
    dbh.select_all(sql) do |row|
        puts row
    end
end

Ruby标准库NET库

1、NET库主要应用于网络编程

Net::HTTP:HTTP超文本传输协议的抽象类,提供访问WWW网站的支持

Net::POP3:电子邮件协议客户端的抽象类,提供访问、接受电子邮件的支持

Net::SMTP:简单邮件传输协议客户端的抽象类,提供发电子邮件的支持

Net::FTP:文件传输协议客户端抽象类,提供网络文件传输存储的支持

Net::Telnet:远程登录服务客户端的抽象类,提供远程登录终端的操作支持

Net::IMAP:邮件获取协议客户端的抽象类,提供了类似于POP3访问接受电子邮件的支持。

2、Net::HTTP抓取网页

Ruby标准库里包含URI库,URI库是一种用于互联网对各种资源(网页、文件)进行定位的地址表述方式

require "uri"
#URI:网址解析
URI.split("http://www.ruby-lang.org/") # => ["http", nil, "www.ruby-lang.org", nil, nil, "/", nil, nil, nil]
URI.join('http://www.ruby-lang.org/', '/ja/man-1.6/') # => <URI::HTTP:0x2010017a URL:http://www.ruby-lang.org/ja/man-1.6/>
URI.escape('http://www.ruby-lang.org/ja/man-1.6/?cmd=view;name=Ruby参考手册')
URI.encode('http://www.ruby-lang.org/ja/man-1.6/?cmd=view;name=Ruby参考手册')
# => "http://www.ruby-lang.org/ja/man-1.6/?cmd=view;name=Ruby%A5%EA%A5%D5%A5%A1%A5%EC%A5%F3%A5%B9%A5%DE%A5%CB%A5%E5%A5%A2%A5%EB"

URI.unescape('http://www.ruby-lang.org/ja/man-1.6/?cmd=view;name=Ruby%A5%EA%A5%D5%A5%A1%A5%EC%A5%F3%A5%B9%A5%DE%A5%CB%A5%E5%A5%A2%A5%EB')
URI.decode('http://www.ruby-lang.org/ja/man-1.6/?cmd=view;name=Ruby%A5%EA%A5%D5%A5%A1%A5%EC%A5%F3%A5%B9%A5%DE%A5%CB%A5%E5%A5%A2%A5%EB')
# => "http://www.ruby-lang.org/ja/man-1.6/?cmd=view;name=Ruby参考手册"

# uri可使用方法:[userinfo, host, port, path, query, fragment]
uri = URI.parse("http://www.ruby-lang.org/") # => #<URI::HTTP:0x201002a6 URL:http://www.ruby-lang.org/>
    
require "net/http"
#以get的方式访问网站,以字符串形式返回服务器回应
#get(uri_or_host,path=nil,port=nil)
puts Net::HTTP.get("www.baidu.com","/")
puts Net::HTTP.get(URI.parse("http://www.baidu.com"))

#获取服务器响应附加信息
response=Net::HTTP.get_response(URI.parse("http://www.baidu.com"))
puts response.code
puts response.body

#发送post请求
response=Net::HTTP.post_form(URI.parse("http://passport.baidu.com"),{:username => "",password => ""})

#代理访问
proxy_addr='192.168.0.1'
proxy_port=8080
uri=URI.parse("http://www.baidu.com")

#创建代理服务器
res=Net::HTTP::Proxy(proxy_addr,proxy_port).start(uri.host){|http| http.get(uri.path)}
puts res.body

3、Net::POP3收取邮件

require 'net/pop'
    
pop=Net::POP3.new('pop3.sina.com.cn')
pop.start('username','password')
if pop.mails.empty?
    puts "no email"
else
    i=0
    pop.mails.each do |popmail|
        File.open("") do |f|
            f.write popmail.pop
        end
        popmail.delete
        i=i+1
    end
end
pop.finish

4、Net::SMTP发送邮件

require 'net/smtp'

Net::SMTP.start('smtp.sina.com.cn',25,'mail.sina.com','username','password',:login) do |smtp|
    smtp.send_message("html","发件人邮箱","收件人邮箱")
end

5、Net::FTP

require 'net/ftp'
    
Net::FTP.open('ftp地址') do |ftp|
    ftp.login
    ftp.chdir('/')
    #列出根目录下所有文件
    files=ftp.nlst
    files.each{|file| puts file}
        
    #下载
    ftp.gettextfile('read.txt'){|line| puts line}

Ruby对Win32API和Win32OLE支持

1、Win32API是Windows操作系统内核与应用程序之间的接口。

2、Win32OLE是一项增强Windows应用程序之间的相互协作性的技术。比如操作word、excel、控制浏览器等

Ruby构建图形界面

1、Ruby/Tk

2、WxRuby

3、Shoes

扩展库(rest-client)Ruby访问url传递参数

require 'rest-client'
#Get方式获取HTTP跟https
response = RestClient.get('http://example.com/resource?count=10')
response = RestClient.get('http://example.com/resource', {:params => {:id => 50, 'foo' => 'bar'}})
response =RestClient.get('https://httpbin.org/get', params: {foo: 'bar', baz: 'qux'})
#GET "https://httpbin.org/get?foo=bar&baz=qux"
RestClient.get('https://http-params.herokuapp.com/get', params: {foo: [1,2,3]})
#GET "https://http-params.herokuapp.com/get?foo[]=1&foo[]=2&foo[]=3"
RestClient.get('https://http-params.herokuapp.com/get', params: {outer: {foo: 123, bar: 456}})
#GET "https://http-params.herokuapp.com/get?outer[foo]=123&outer[bar]=456"
RestClient.get('https://httpbin.org/get', params:RestClient::ParamsArray.new([[:foo, 1], [:foo, 2]]))
#GET "https://httpbin.org/get?foo=1&foo=2"
RestClient.get('https://httpbin.org/get', params: {foo: RestClient::ParamsArray.new([[:a, 1], [:a, 2]])})
#GET "https://httpbin.org/get?foo[a]=1&foo[a]=2"
response = RestClient.get('https://user:password@example.com/private/resource', {:accept => :json})
puts response.body ? JSON.load(response.body) : {}
response.headers

#Post方式获取http跟https
response = RestClient.post('http://example.com/resource', :param1 => 'one', :nested => { :param2 => 'two' })
response = RestClient.post('https://httpbin.org/post', {foo: 'bar', baz: 'qux'})
#POST "https://httpbin.org/post", data: "foo=bar&baz=qux"
response = RestClient.post("http://example.com/resource", { 'x' => 1 }.to_json, :content_type => :json, :accept => :json)
response = RestClient.post("http://example.com/resource",{:media => File.new(filename,'rb'),:multipart => true})
response = RestClient.post('/data', :myfile => File.new("/path/to/image.jpg", 'rb'))
puts response.body ? JSON.load(response.body) : {}
response.headers

#delete方式获取http跟https
RestClient.delete 'http://example.com/resource'

#RestClient::Request方式
RestClient::Request.execute(method: :get, url: 'http://example.com/resource',
                        timeout: 10)

RestClient::Request.execute(method: :get, url: 'http://example.com/resource',
                        ssl_ca_file: 'myca.pem',
                        ssl_ciphers: 'AESGCM:!aNULL')

RestClient::Request.execute(method: :get, url: 'http://example.com/resource',
                        timeout: 10, headers: {params: {foo: 'bar'}})

RestClient::Request.execute(method: :delete, url: 'http://example.com/resource',
                        payload: 'foo', headers: {myheader: 'bar'})