Sha256: 0fb488fdfda198029af935a82d512fb66f76823d2df5c268e9dba79f10818ea4

Contents?: true

Size: 1.71 KB

Versions: 2

Compression:

Stored size: 1.71 KB

Contents

# inits and saves postgre
#   string and integer arrays
#   hstore as hash with indifferent access to keys

module Sequel::Plugins::LuxArrayAndHstore
  module ClassMethods
  end

  module DatasetMethods
  end

  module InstanceMethods
    # set right values on
    def after_initialize
      db_schema.each do |field, schema|
        type = schema[:db_type]
        if type.include?('[]') && !self[field].is_a?(Array)
          self[field] = self[field].to_s.gsub(/^\{|\}$/, '').split(',')
          self[field] = self[field].map(&:to_i) if schema[:type] == :integer
        elsif type == 'jsonb'
          self[field] ||= {}
          self[field] = HashWithIndifferentAccess.new(JSON.load(self[field]) || {})
        end
      end
    end

    def before_save
      @_array_hash_cache_fields = {}

      db_schema.each do |field, schema|
        if schema[:db_type].include?('[]')
          @_array_hash_cache_fields[field] = self[field].dup

          data = self[field].to_a
          data = data.map(&:to_i) if schema[:type] == :integer

          db_data = data.to_json
          db_data[0,1] = '{'
          db_data[-1,1] = '}'
          self[field] = db_data
        elsif ['json', 'jsonb'].index(schema[:db_type])
          @_array_hash_cache_fields[field] = self[field].dup

          # we use this to convert symbols in keys to strings
          self[field] = JSON.load(self[field].to_json).to_json
        elsif schema[:db_type] == 'boolean'
          self[field] = false if self[field] == 0
          self[field] = true  if self[field] == 1
        end
      end

      super
    end

    def after_save
      @_array_hash_cache_fields.each { |k, v| self[k] = v }

      super
    end
  end

end

Sequel::Model.plugin :lux_array_and_hstore

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
lux-fw-0.1.35 ./lib/plugins/db_helpers/array_and_hstore.rb
lux-fw-0.1.17 ./lib/plugins/db_helpers/array_and_hstore.rb