Class: String
- Inherits:
-
Object
- Object
- String
- Defined in:
- lib/activerecord-postgres-array/string.rb
Instance Method Summary collapse
-
#from_postgres_array(base_type = :string) ⇒ Object
Creates an array from a postgres array string that postgresql spits out.
- #to_postgres_array ⇒ Object
-
#valid_postgres_array? ⇒ Boolean
Validates the array format.
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 38 39 40 41 |
# File 'lib/activerecord-postgres-array/string.rb', line 19 def from_postgres_array(base_type = :string) if empty? [] else elements = match(/\{(.*)\}/m).captures.first.gsub(/\\"/, '$ESCAPED_DOUBLE_QUOTE$').split(/(?:,)(?=(?:[^"]|"[^"]*")*$)/m) 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 == :float elements.collect(&:to_f) elsif base_type == :integer || base_type == :bigint elements.collect(&:to_i) elsif base_type == :timestamp elements.collect(&:to_time) else elements end end end |
#to_postgres_array ⇒ Object
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”}’
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 |