Class: ChupaText::VirtualContent

Inherits:
Object
  • Object
show all
Defined in:
lib/chupa-text/virtual-content.rb

Constant Summary collapse

INLINE_MAX_SIZE =
64 * 1024

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input, original_path = nil) ⇒ VirtualContent

Returns a new instance of VirtualContent.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/chupa-text/virtual-content.rb', line 26

def initialize(input, original_path=nil)
  if original_path.is_a?(String)
    if original_path.empty?
      original_path = nil
    else
      original_path = Pathname.new(original_path)
    end
  end
  @original_path = original_path
  body = input.read(INLINE_MAX_SIZE + 1) || ""
  if body.bytesize <= INLINE_MAX_SIZE
    @body = body
    @size = @body.bytesize
    @file = nil
    @path = nil
  else
    @body = nil
    setup_file do |file|
      file.write(body)
      @size = body.bytesize
      @size += IO.copy_stream(input, file)
    end
  end
end

Instance Attribute Details

#sizeObject (readonly)

Returns the value of attribute size.



25
26
27
# File 'lib/chupa-text/virtual-content.rb', line 25

def size
  @size
end

Instance Method Details

#bodyObject



67
68
69
70
71
72
73
74
75
# File 'lib/chupa-text/virtual-content.rb', line 67

def body
  if @body
    @body
  else
    open do |file|
      file.read
    end
  end
end

#open(&block) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/chupa-text/virtual-content.rb', line 51

def open(&block)
  if @body
    yield(StringIO.new(@body))
  else
    File.open(path, "rb", &block)
  end
end

#pathObject



87
88
89
90
91
92
93
94
# File 'lib/chupa-text/virtual-content.rb', line 87

def path
  if @path.nil?
    setup_file do |file|
      file.write(@body)
    end
  end
  @path
end

#peek_body(size) ⇒ Object



77
78
79
80
81
82
83
84
85
# File 'lib/chupa-text/virtual-content.rb', line 77

def peek_body(size)
  if @body
    @body[0, size]
  else
    open do |file|
      file.read(size)
    end
  end
end

#releaseObject



59
60
61
62
63
64
65
# File 'lib/chupa-text/virtual-content.rb', line 59

def release
  @body = nil
  if @file
    @file.delete
    @file = nil
  end
end