Module: ASModel::DatabaseMapping::ClassMethods

Defined in:
backend/app/model/ASModel_database_mapping.rb

Constant Summary collapse

JSON_TO_DB_MAPPINGS =
{
  'boolean' => {
    :description => "JSON booleans become DB integers",
    :json_to_db => ->(bool) { bool ? 1 : 0 },
    :db_to_json => ->(int) { int === 1 }
  },
  'date' => {
    :description => "Date strings become dates",
    :json_to_db => ->(s) { s.nil? ? s : Date.parse(s) },
    :db_to_json => ->(date) { date.nil? ? date : date.strftime('%Y-%m-%d') }
  }
}

Instance Method Summary collapse

Instance Method Details

#map_db_types_to_json(schema, hash) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'backend/app/model/ASModel_database_mapping.rb', line 45

def map_db_types_to_json(schema, hash)
  hash = hash.clone
  schema['properties'].each do |property, definition|
    mapping = JSON_TO_DB_MAPPINGS[definition['type']]

    property = property.intern
    if mapping && hash.has_key?(property)
      hash[property] = mapping[:db_to_json].call(hash[property])
    end
  end

  hash
end

#prepare_for_db(jsonmodel_class, hash) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'backend/app/model/ASModel_database_mapping.rb', line 24

def prepare_for_db(jsonmodel_class, hash)
  schema = jsonmodel_class.schema
  hash = hash.clone
  schema['properties'].each do |property, definition|
    mapping = JSON_TO_DB_MAPPINGS[definition['type']]
    if mapping && hash.has_key?(property)
      hash[property] = mapping[:json_to_db].call(hash[property])
    end
  end

  nested_records.each do |nested_record|
    # Nested records will be processed separately.
    hash.delete(nested_record[:json_property].to_s)
  end

  hash['json_schema_version'] = jsonmodel_class.schema_version

  hash
end