Class: IO

Inherits:
Object show all
Includes:
Puppet::Util::MonkeyPatches::Lines
Defined in:
lib/puppet/util/monkey_patches.rb

Class Method Summary collapse

Methods included from Puppet::Util::MonkeyPatches::Lines

#lines

Class Method Details

.binread(name, length = nil, offset = 0) ⇒ Object



112
113
114
115
116
117
118
# File 'lib/puppet/util/monkey_patches.rb', line 112

def self.binread(name, length = nil, offset = 0)
  Puppet.deprecation_warning("This is a monkey-patched implementation of IO.binread on ruby 1.8 and is deprecated. Read the file without this method as it will be removed in a future version.")
  File.open(name, 'rb') do |f|
    f.seek(offset) if offset > 0
    f.read(length)
  end
end

.binwrite(name, string, offset = nil) ⇒ Object



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/puppet/util/monkey_patches.rb', line 120

def self.binwrite(name, string, offset = nil)
  # Determine if we should truncate or not.  Since the truncate method on a
  # file handle isn't implemented on all platforms, safer to do this in what
  # looks like the libc / POSIX flag - which is usually pretty robust.
  # --daniel 2012-03-11
  mode = Fcntl::O_CREAT | Fcntl::O_WRONLY | (offset.nil? ? Fcntl::O_TRUNC : 0)

  # We have to duplicate the mode because Ruby on Windows is a bit precious,
  # and doesn't actually carry over the mode.  It won't work to just use
  # open, either, because that doesn't like our system modes and the default
  # open bits don't do what we need, which is awesome. --daniel 2012-03-30
  IO.open(IO::sysopen(name, mode), mode) do |f|
    # ...seek to our desired offset, then write the bytes.  Don't try to
    # seek past the start of the file, eh, because who knows what platform
    # would legitimately blow up if we did that.
    #
    # Double-check the positioning, too, since destroying data isn't my idea
    # of a good time. --daniel 2012-03-11
    target = [0, offset.to_i].max
    unless (landed = f.sysseek(target, IO::SEEK_SET)) == target
      raise "unable to seek to target offset #{target} in #{name}: got to #{landed}"
    end

    f.syswrite(string)
  end
end