Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/activerecord_postgres_hstore_core/string.rb

Instance Method Summary collapse

Instance Method Details

#from_hstoreObject

Creates a hash from a valid double quoted hstore format, ‘cause this is the format that postgresql spits out.



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/activerecord_postgres_hstore_core/string.rb', line 21

def from_hstore
  token_pairs = (scan(hstore_pair)).map { |k,v| [k,v =~ /^NULL$/i ? nil : v] }
  token_pairs = token_pairs.map { |k,v|
    [k,v].map { |t| 
      case t
      when nil then t
      when /\A"(.*)"\Z/m then $1.gsub(/\\(.)/, '\1')
      else t.gsub(/\\(.)/, '\1')
      end
    }
  }
  Hash[ token_pairs ]
end

#to_hstoreObject

If the value os a column is already a String and it calls to_hstore, it just returns self. Validation occurs afterwards.



5
6
7
# File 'lib/activerecord_postgres_hstore_core/string.rb', line 5

def to_hstore
  self
end

#valid_hstore?Boolean

Validates the hstore format. Valid formats are:

  • An empty string

  • A string like %(“foo”=>“bar”). I’ll call it a “double quoted hstore format”.

  • A string like %(foo=>bar). Postgres doesn’t emit this but it does accept it as input, we should accept any input Postgres does

Returns:

  • (Boolean)


14
15
16
17
# File 'lib/activerecord_postgres_hstore_core/string.rb', line 14

def valid_hstore?
  pair = hstore_pair
  !!match(/^\s*(#{pair}\s*(,\s*#{pair})*)?\s*$/)
end