Class: Y2Network::Bitrate

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
src/lib/y2network/bitrate.rb

Overview

Represents a bitrate

This class is not as generic as Y2Storage::DiskSize and it is used to support parsing bitrates information from iwlist. However, it could be extended in the future if needed.

Defined Under Namespace

Classes: ParseError

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(bits) ⇒ Bitrate

Returns a new instance of Bitrate.

Parameters:

  • bits (Integer)

    Bits



63
64
65
# File 'src/lib/y2network/bitrate.rb', line 63

def initialize(bits)
  @bits = bits
end

Class Method Details

.parse(str) ⇒ Bitrate

Parses a string and converts the value to a string

Examples:

Parsing Mb/s

bitrate = Bitrate.parse("54 Mb/s")
bitrate.to_i #=> 54000000
bitrate.to_s #=> "54 Mb/s"

Parameters:

  • str (String)

    String to parse

Returns:

Raises:

  • ParseError



49
50
51
52
53
54
55
56
57
58
59
# File 'src/lib/y2network/bitrate.rb', line 49

def parse(str)
  match = PARSE_REGEXP.match(str)
  raise ParseError unless match

  number, unit = match.captures
  unit ||= "b"
  power = UNITS.index(unit)
  raise ParseError unless power

  new(number.to_i * (1000**power))
end

Instance Method Details

#<=>(other) ⇒ Integer

Compare two bitrates

Parameters:

Returns:

  • (Integer)


93
94
95
# File 'src/lib/y2network/bitrate.rb', line 93

def <=>(other)
  to_i <=> other.to_i
end

#to_iInteger

Return the bits

Returns:

  • (Integer)

    Return the bits



68
69
70
# File 'src/lib/y2network/bitrate.rb', line 68

def to_i
  @bits
end

#to_sString

Returns the string representation of the bitrate

It automatically selects the unit to use depending on the bitrate value.

Returns:

  • (String)

    String representation



77
78
79
80
81
82
83
84
85
86
87
# File 'src/lib/y2network/bitrate.rb', line 77

def to_s
  power = (0..UNITS.length - 1).to_a.reverse.find do |u|
    to_i > (1000**u)
  end

  units = UNITS[power]
  number = @bits.to_f / (1000**power)
  number_str = number.to_s.sub(".0", "") # strip insignificant zeroes

  "#{number_str} #{units}/s"
end