Class: Resolv::Hosts

Inherits:
Object
  • Object
show all
Defined in:
lib/logmerge/resolv.rb

Constant Summary collapse

DefaultFileName =
'/etc/hosts'

Instance Method Summary collapse

Constructor Details

#initialize(filename = DefaultFileName) ⇒ Hosts

Returns a new instance of Hosts.



292
293
294
295
296
# File 'lib/logmerge/resolv.rb', line 292

def initialize(filename = DefaultFileName)
  @filename = filename
  @mutex = Mutex.new
  @initialized = nil
end

Instance Method Details

#each_address(name, &proc) ⇒ Object



340
341
342
343
344
345
# File 'lib/logmerge/resolv.rb', line 340

def each_address(name, &proc)
  lazy_initialize
  if @name2addr.include?(name)
    @name2addr[name].each(&proc)
  end
end

#each_name(address, &proc) ⇒ Object



358
359
360
361
362
363
# File 'lib/logmerge/resolv.rb', line 358

def each_name(address, &proc)
  lazy_initialize
  if @addr2name.include?(address)
    @addr2name[address].each(&proc)
  end
end

#getaddress(name) ⇒ Object

Raises:



329
330
331
332
# File 'lib/logmerge/resolv.rb', line 329

def getaddress(name)
  each_address(name) {|address| return address}
  raise ResolvError.new("#{@filename} has no name: #{name}")
end

#getaddresses(name) ⇒ Object



334
335
336
337
338
# File 'lib/logmerge/resolv.rb', line 334

def getaddresses(name)
  ret = []
  each_address(name) {|address| ret << address}
  return ret
end

#getname(address) ⇒ Object

Raises:



347
348
349
350
# File 'lib/logmerge/resolv.rb', line 347

def getname(address)
  each_name(address) {|name| return name}
  raise ResolvError.new("#{@filename} has no address: #{address}")
end

#getnames(address) ⇒ Object



352
353
354
355
356
# File 'lib/logmerge/resolv.rb', line 352

def getnames(address)
  ret = []
  each_name(address) {|name| ret << name}
  return ret
end

#lazy_initializeObject



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/logmerge/resolv.rb', line 298

def lazy_initialize
  @mutex.synchronize {
    unless @initialized
      @name2addr = {}
      @addr2name = {}
      open(@filename) {|f|
        f.each {|line|
          line.sub!(/#.*/, '')
          addr, hostname, *aliases = line.split(/\s+/)
          next unless addr
          addr.untaint
          hostname.untaint
          @addr2name[addr] = [] unless @addr2name.include? addr
          @addr2name[addr] << hostname
          @addr2name[addr] += aliases
          @name2addr[hostname] = [] unless @name2addr.include? hostname
          @name2addr[hostname] << addr
          aliases.each {|n|
            n.untaint
            @name2addr[n] = [] unless @name2addr.include? n
            @name2addr[n] << addr
          }
        }
      }
      @name2addr.each {|name, arr| arr.reverse!}
      @initialized = true
    end
  }
  self
end