Class: Sequel::Postgres::HStore
- Inherits:
-
Hash
- Object
- Hash
- Sequel::Postgres::HStore
- Defined in:
- lib/hstore/hstore.rb
Class Method Summary collapse
- .new_from_string(string) ⇒ Object
- .parse_quotable_string(scanner) ⇒ Object
- .quoted_string(scanner) ⇒ Object
- .skip_key_value_delimiter(scanner) ⇒ Object
- .skip_pair_delimiter(scanner) ⇒ Object
Instance Method Summary collapse
-
#initialize(hash) ⇒ HStore
constructor
A new instance of HStore.
- #sql_literal(dataset) ⇒ Object
- #to_s_escaped(str) ⇒ Object
Constructor Details
#initialize(hash) ⇒ HStore
Returns a new instance of HStore.
47 48 49 |
# File 'lib/hstore/hstore.rb', line 47 def initialize(hash) @hash = hash end |
Class Method Details
.new_from_string(string) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/hstore/hstore.rb', line 28 def self.new_from_string(string) hash = {} # remove single quotes around literal if necessary string = string[1..-2] if string[0] == "'" and string[-1] == "'" scanner = StringScanner.new(string) while !scanner.eos? k = parse_quotable_string(scanner) skip_key_value_delimiter(scanner) v = parse_quotable_string(scanner) skip_pair_delimiter(scanner) # controversial... # to_sym, or what? hash[k.to_sym] = v end self[hash] end |
.parse_quotable_string(scanner) ⇒ Object
10 11 12 13 14 15 16 17 18 |
# File 'lib/hstore/hstore.rb', line 10 def self.parse_quotable_string(scanner) if scanner.scan(/"/) value = quoted_string(scanner) else value = scanner.scan(/\w+/) value = nil if value == "NULL" # TODO: values but not keys may be NULL end end |
.quoted_string(scanner) ⇒ Object
4 5 6 7 8 9 |
# File 'lib/hstore/hstore.rb', line 4 def self.quoted_string(scanner) key = scanner.scan(/(\\"|[^"])*/) key = key.gsub(/\\(.)/, '\1') scanner.skip(/"/) key end |
.skip_key_value_delimiter(scanner) ⇒ Object
20 21 22 |
# File 'lib/hstore/hstore.rb', line 20 def self.skip_key_value_delimiter(scanner) scanner.skip(/\s*=>\s*/) end |
.skip_pair_delimiter(scanner) ⇒ Object
24 25 26 |
# File 'lib/hstore/hstore.rb', line 24 def self.skip_pair_delimiter(scanner) scanner.skip(/,\s*/) end |
Instance Method Details
#sql_literal(dataset) ⇒ Object
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/hstore/hstore.rb', line 55 def sql_literal(dataset) string = self.map do |(k,v)| if v.nil? # represent nil as NULL without quotes v = "NULL" else # otherwise, write a double-quoted string with backslash escapes for quotes v = to_s_escaped(v) v = "\"#{v}\"" end # TODO: throw an error if there is a NULL key "\"#{to_s_escaped(k)}\" => #{v}" end.join(", ") "'#{string}'" end |
#to_s_escaped(str) ⇒ Object
51 52 53 |
# File 'lib/hstore/hstore.rb', line 51 def to_s_escaped(str) str.to_s.gsub(/\\(?!")/) {'\\\\'}.gsub(/"/, '\"').gsub(/'/, "''") end |