Class: DataAPI::Schema

Inherits:
ActiveSupport::HashWithIndifferentAccess
  • Object
show all
Defined in:
app/models/data_api/schema.rb

Constant Summary collapse

COLUMN_ATTRS =
{
  'uuid' => String,
  'type' => String,
  'index' => Boolean
}
COLUMN_TYPES =
%w(string integer float boolean text datetime)
RESERVED_COLUMN_NAMES =
ActiveRecord::Base.instance_methods.map(&:to_s)

Instance Method Summary collapse

Constructor Details

#initialize(constructor = {}, skip_check = false) ⇒ Schema


10
11
12
13
14
15
16
17
18
19
20
21
# File 'app/models/data_api/schema.rb', line 10

def initialize(constructor = {}, skip_check = false)
  fail unless constructor.is_a?(String)
  super(JSON.parse(constructor))
rescue
  super(constructor)
ensure
  return if skip_check
  clear_invalid_columns
  generate_uuid_for_new_columns
  set_default_type_for_columns
  sort_column_attrs
end

Instance Method Details

#load_from_array(columns) ⇒ Object


23
24
25
26
27
28
29
30
31
32
33
34
# File 'app/models/data_api/schema.rb', line 23

def load_from_array(columns)
  clear

  columns.each do |column|
    column.stringify_keys!
    next if !column.is_a?(Hash) || column['name'].blank?
    self[column['name']] = column.clone
    self[column['name']][:index] = true if self[column['name']][:index] == 'true'
  end

  validate!
end

#position_of(key) ⇒ Object


95
96
97
# File 'app/models/data_api/schema.rb', line 95

def position_of(key)
  COLUMN_ATTRS.keys.index(key) || key.ord
end

#to_hash_indexed_with_uuidObject


48
49
50
51
52
53
54
55
56
# File 'app/models/data_api/schema.rb', line 48

def to_hash_indexed_with_uuid
  HashWithIndifferentAccess.new(
    Hash[
      map do |column_name, column_attrs|
        [column_attrs[:uuid], column_attrs.merge('name' => column_name)]
      end
    ]
  )
end

#to_sObject


44
45
46
# File 'app/models/data_api/schema.rb', line 44

def to_s
  to_json
end

#validate!Object


36
37
38
39
40
41
42
# File 'app/models/data_api/schema.rb', line 36

def validate!
  clear_invalid_columns
  generate_uuid_for_new_columns
  set_default_type_for_columns
  clear_duplicated_uuid_columns
  sort_column_attrs
end