Class: Perpetuity::Postgres::SerializedData

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/perpetuity/postgres/serialized_data.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(column_names, *values) ⇒ SerializedData

Returns a new instance of SerializedData.



8
9
10
11
# File 'lib/perpetuity/postgres/serialized_data.rb', line 8

def initialize column_names, *values
  @column_names = column_names.map(&:to_s)
  @values = values
end

Instance Attribute Details

#column_namesObject (readonly)

Returns the value of attribute column_names.



7
8
9
# File 'lib/perpetuity/postgres/serialized_data.rb', line 7

def column_names
  @column_names
end

#valuesObject (readonly)

Returns the value of attribute values.



7
8
9
# File 'lib/perpetuity/postgres/serialized_data.rb', line 7

def values
  @values
end

Instance Method Details

#+(other) ⇒ Object



34
35
36
37
38
39
# File 'lib/perpetuity/postgres/serialized_data.rb', line 34

def + other
  combined = self.class.new(column_names.dup, *(values.dup))
  combined.values << other.values

  combined
end

#-(other) ⇒ Object



51
52
53
54
55
56
57
58
59
# File 'lib/perpetuity/postgres/serialized_data.rb', line 51

def - other
  values = self.values.first
  modified_values = values - other.values.first
  modified_columns = column_names.select.with_index { |col, index|
    values[index] != other.values.first[index]
  }

  SerializedData.new(modified_columns, modified_values)
end

#==(other) ⇒ Object



61
62
63
64
65
# File 'lib/perpetuity/postgres/serialized_data.rb', line 61

def == other
  other.is_a? SerializedData and
  other.column_names == column_names and
  other.values == values
end

#[](key) ⇒ Object



18
19
20
21
# File 'lib/perpetuity/postgres/serialized_data.rb', line 18

def [] key
  index = column_names.index(key.to_s)
  values.first[index]
end

#[]=(column, value) ⇒ Object



23
24
25
26
27
28
29
30
31
32
# File 'lib/perpetuity/postgres/serialized_data.rb', line 23

def []= column, value
  value = TextValue.new(value)
  if column_names.include? column
    index = column_names.index(column)
    values.first[index] = value
  else
    column_names << column
    values.first << value
  end
end

#any?Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/perpetuity/postgres/serialized_data.rb', line 41

def any?
  values.flatten.any?
end

#eachObject



45
46
47
48
49
# File 'lib/perpetuity/postgres/serialized_data.rb', line 45

def each
  data = values.first
  column_names.each_with_index { |column, index| yield(column, data[index]) }
  self
end

#to_sObject



13
14
15
16
# File 'lib/perpetuity/postgres/serialized_data.rb', line 13

def to_s
  value_strings = values.map { |data| "(#{data.join(',')})" }.join(',')
  "(#{column_names.join(',')}) VALUES #{value_strings}"
end