Class: Graphlyte::Syntax::NumericLiteral

Inherits:
Data
  • Object
show all
Defined in:
lib/graphlyte/syntax.rb

Overview

A representation of a GraphQL literal, preserving the text components

Note: NumericLiterals are immutable.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Data

#==, attr_accessor, attr_reader, attributes, #dup, #eql?, #hash, #inspect

Constructor Details

#initialize(**kwargs) ⇒ NumericLiteral

Returns a new instance of NumericLiteral.

Raises:

  • (ArgumentError)


316
317
318
319
320
321
322
323
# File 'lib/graphlyte/syntax.rb', line 316

def initialize(**kwargs)
  super
  @negated ||= false

  raise ArgumentError, 'integer_part is required' unless @integer_part

  freeze
end

Instance Attribute Details

#exponent_partObject

Returns the value of attribute exponent_part.



314
315
316
# File 'lib/graphlyte/syntax.rb', line 314

def exponent_part
  @exponent_part
end

#fractional_partObject

Returns the value of attribute fractional_part.



314
315
316
# File 'lib/graphlyte/syntax.rb', line 314

def fractional_part
  @fractional_part
end

#integer_partObject

Returns the value of attribute integer_part.



314
315
316
# File 'lib/graphlyte/syntax.rb', line 314

def integer_part
  @integer_part
end

#negatedObject

Returns the value of attribute negated.



314
315
316
# File 'lib/graphlyte/syntax.rb', line 314

def negated
  @negated
end

Instance Method Details

#floating?Boolean

Returns:

  • (Boolean)


325
326
327
# File 'lib/graphlyte/syntax.rb', line 325

def floating?
  !!@fractional_part || !!@exponent_part
end

#to_fObject



343
344
345
346
347
348
349
# File 'lib/graphlyte/syntax.rb', line 343

def to_f
  n = to_i.to_f
  n += fractional_value if fractional_part
  n *= exponent_value if exponent_part

  n
end

#to_iObject



339
340
341
# File 'lib/graphlyte/syntax.rb', line 339

def to_i
  unnegate(negated, integer_part.to_i)
end

#to_sObject



329
330
331
332
333
334
335
336
337
# File 'lib/graphlyte/syntax.rb', line 329

def to_s
  s = "#{negated ? '-' : ''}#{integer_part}"
  return s unless floating?

  s << ".#{fractional_part}" if fractional_part
  s << "e#{exponent_part.first}#{exponent_part.last}" if @exponent_part

  s
end