Ruby module OpenURI to get http/FTP address content

Source: Internet
Author: User

Ruby has some special modules that are useful. For example, the Ruby module OpenURI introduced here is a common Ruby module. We need to be familiar with its features.

  • Ruby on Rails directory files
  • Ruby function pointer concepts
  • Ruby Rmagick Installation Guide
  • Ruby special syntax concepts
  • Example of Ruby code for getting the current class name

To obtain the content of an HTTP/FTP address in Ruby, you can easily use the open-uri library.

Ruby module OpenURI is included in ruby's standard additional library, path: lib/oepn-uri.rb

After referencing this additional library, you can open the resource of an http/ftp uri just like opening a common file.

The differences between the Ruby module OpenURI are as follows:

  1. Require 'open-uri'
  2. Open ('C:/boot. ini ') {| file |
  3. Puts file. class # File
  4. }
  5. Open ('HTTP: // coderlee.
    Cnblogs.com ') {| file |
  6. Puts file. class # Tempfile
  7. }

It can be seen that the block parameter for opening a local File is of the File type, while the block parameter for opening a uri is of the Tempfile type.

Note that the open method in open-uri will automatically track access to the 302 redirection address, while the Net: HTTP # get method will not automatically track the 302 redirection address.

The final value returned by this function is the final value of the incoming code block. You can obtain the OpenURI content of the Ruby module in this way.

 
 
  1. data = open('http://coderlee.
    cnblogs.com'){|f| f.read}  
  2. data = open('http://coderlee.
    cnblogs.com'){|f| f}.open.read 

The reason for the second open statement is that the stream returned by the open method is the closed tempfile. Therefore, open the stream first, return the opened stream, and then call read to read the stream.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.