Class: Typero::HashType

Inherits:
Type
  • Object
show all
Defined in:
lib/typero/type/types/hash_type.rb

Constant Summary

Constants inherited from Type

Type::ERRORS, Type::OPTS, Type::OPTS_KEYS

Instance Attribute Summary

Attributes inherited from Type

#opts

Instance Method Summary collapse

Methods inherited from Type

allowed_opt?, #db_field, db_schema, error, #get, #initialize, load, opts, #value

Constructor Details

This class inherits a constructor from Typero::Type

Instance Method Details

#db_schemaObject



25
26
27
28
29
30
# File 'lib/typero/type/types/hash_type.rb', line 25

def db_schema
  [:jsonb, {
    null: false,
    default: '{}'
  }]
end

#defaultObject



21
22
23
# File 'lib/typero/type/types/hash_type.rb', line 21

def default
  {}
end

#setObject



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/typero/type/types/hash_type.rb', line 4

def set
  if value.is_a?(String) && value[0,1] == '{'
    @value = JSON.parse(value)
  end

  @value ||= {}
  @value.delete_if {|_, v| v.respond_to?(:empty?) && v.empty? }

  error_for(:not_hash_type_error) unless @value.respond_to?(:keys) && @value.respond_to?(:values)

  if opts[:allow]
    for key in @value.keys
      @value.delete(key) unless opts[:allow].include?(key)
    end
  end
end