Class: Scaruby::IO::Source

Inherits:
Object show all
Defined in:
lib/scaruby/io.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string_io) ⇒ Source

Returns a new instance of Source.



12
13
14
15
# File 'lib/scaruby/io.rb', line 12

def initialize(string_io)
  assert_type(string_io, StringIO)
  @string_io = string_io
end

Instance Attribute Details

#string_ioObject (readonly)

Returns the value of attribute string_io.



10
11
12
# File 'lib/scaruby/io.rb', line 10

def string_io
  @string_io
end

Class Method Details

.from_bytes(bytes, encoding = 'UTF-8') ⇒ Object



17
18
19
20
# File 'lib/scaruby/io.rb', line 17

def self.from_bytes(bytes, encoding='UTF-8')
  content = bytes.to_a.pack('c*').force_encoding(encoding)
  Source.new(StringIO.new(content))
end

.from_file(file, encoding = 'UTF-8') ⇒ Object



22
23
24
25
26
27
28
29
30
# File 'lib/scaruby/io.rb', line 22

def self.from_file(file, encoding='UTF-8')
  content = ''
  File::open(file, "r:#{encoding}") do |file|
    while line = file.gets
      content += line
    end
  end
  Source.new(StringIO.new(content))
end

.from_url(url, encoding = 'UTF-8') ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/scaruby/io.rb', line 32

def self.from_url(url, encoding='UTF-8')
  uri = URI.parse(url)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.is_a?(URI::HTTPS)
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  http.start { |http|
    req = Net::HTTP::Get.new(uri.request_uri)
    res = http.request(req)
    Source.new(StringIO.new(res.body))
  }
end

Instance Method Details

#get_linesObject



45
46
47
# File 'lib/scaruby/io.rb', line 45

def get_lines
  Seq.new(@string_io.map { |line| line })
end

#to_seqObject



49
50
51
52
53
54
55
# File 'lib/scaruby/io.rb', line 49

def to_seq
  chars = []
  while @string_io.eof? do
    chars.push(@string_io.getc)
  end
  Seq.new(chars)
end