Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/activerecord-postgres-array/string.rb

Instance Method Summary collapse

Instance Method Details

#from_postgres_array(base_type = :string) ⇒ Object

Creates an array from a postgres array string that postgresql spits out.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/activerecord-postgres-array/string.rb', line 19

def from_postgres_array(base_type = :string)
  if empty?
    []
  else
    elements = match(/\{(.*)\}/).captures.first.gsub(/\\"/, '$ESCAPED_DOUBLE_QUOTE$').split(/(?:,)(?=(?:[^"]|"[^"]*")*$)/)
    elements = elements.map do |e|
      res = e.gsub('$ESCAPED_DOUBLE_QUOTE$', '"').gsub("\\\\", "\\").gsub(/^"/, '').gsub(/"$/, '').gsub("''", "'").strip
      res == 'NULL' ? nil : res
    end

    if base_type == :decimal
      elements.collect(&:to_d)
    elsif base_type == :integer
      elements.collect(&:to_i)
    else
      elements
    end
  end
end

#to_postgres_arrayObject



2
3
4
# File 'lib/activerecord-postgres-array/string.rb', line 2

def to_postgres_array
  self
end

#valid_postgres_array?Boolean

Validates the array format. Valid formats are:

  • An empty string

  • A string like ‘10000, 10000, 10000’

  • TODO A multi dimensional array string like ‘“lunch”, “presentation”}’

Returns:

  • (Boolean)


10
11
12
13
14
15
16
# File 'lib/activerecord-postgres-array/string.rb', line 10

def valid_postgres_array?
  string_regexp = /[^",\\]+/
  quoted_string_regexp = /"[^"\\]*(?:\\.[^"\\]*)*"/
  number_regexp = /[-+]?[0-9]*\.?[0-9]+/
  validation_regexp = /\{\s*((#{number_regexp}|#{quoted_string_regexp}|#{string_regexp})(\s*\,\s*(#{number_regexp}|#{quoted_string_regexp}|#{string_regexp}))*)?\}/
  !!match(/^\s*('#{validation_regexp}'|#{validation_regexp})?\s*$/)
end