Class: KDL::Value

Inherits:
Object
  • Object
show all
Defined in:
lib/kdl/value.rb

Defined Under Namespace

Classes: Boolean, Float, Int, NullImpl, String

Constant Summary collapse

Null =
NullImpl.new

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value, format: nil, type: nil) ⇒ Value

Returns a new instance of Value.



5
6
7
8
9
# File 'lib/kdl/value.rb', line 5

def initialize(value, format: nil, type: nil)
  @value = value
  @format = format
  @type = type
end

Instance Attribute Details

#formatObject (readonly)

Returns the value of attribute format.



3
4
5
# File 'lib/kdl/value.rb', line 3

def format
  @format
end

#typeObject (readonly)

Returns the value of attribute type.



3
4
5
# File 'lib/kdl/value.rb', line 3

def type
  @type
end

#valueObject (readonly)

Returns the value of attribute value.



3
4
5
# File 'lib/kdl/value.rb', line 3

def value
  @value
end

Class Method Details

.from(value) ⇒ Object



91
92
93
94
95
96
97
98
99
100
# File 'lib/kdl/value.rb', line 91

def self.from(value)
  case value
  when ::String then String.new(value)
  when Integer then Int.new(value)
  when ::Float then Float.new(value)
  when TrueClass, FalseClass then Boolean.new(value)
  when NilClass then Null
  else raise Error("Unsupported value type: #{value.class}")
  end
end

Instance Method Details

#as_type(type, parser = nil) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/kdl/value.rb', line 11

def as_type(type, parser = nil)
  if parser.nil?
    self.class.new(value, format: format, type: type)
  else
    result = parser.call(self, type)
    return self.as_type(type) if result.nil?

    unless result.is_a?(::KDL::Value)
      raise ArgumentError, "expected parser to return an instance of ::KDL::Value, got `#{result.class}'"
    end

    result
  end
end

#stringify_valueObject



32
33
34
35
36
# File 'lib/kdl/value.rb', line 32

def stringify_value
  return format % value if format

  value.to_s
end

#to_sObject



26
27
28
29
30
# File 'lib/kdl/value.rb', line 26

def to_s
  return stringify_value unless type

  "(#{StringDumper.stringify_identifier type})#{stringify_value}"
end