Module: Parse::Properties

Included in:
Object
Defined in:
lib/parse/model/core/properties.rb

Overview

This module provides support for handling all the different types of column data types supported in Parse and mapping them between their remote names with their local ruby named attributes.

Defined Under Namespace

Modules: ClassMethods Classes: TypecastError

Constant Summary collapse

TYPES =

These are the base types supported by Parse.

[:string, :relation, :integer, :float, :number, :boolean, :date, :array, :file, :geopoint, :polygon, :bytes, :object, :acl, :timezone, :phone, :email, :vector].freeze
NUMERIC_TYPES =

Local data types stored in a Parse Number column.

[:integer, :float, :number].freeze
NUMBER_STRING_FORMAT =

Decimal number literal accepted by typecast_number for String input.

/\A[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?\z/.freeze
EXTRA_FALSE_STRINGS =

String forms read as false for a :boolean property, in addition to ActiveModel's set ("0", "f", "false", "off", and their upper-case forms).

%w[no n].freeze
MUTABLE_TRACKED_TYPES =

Property types whose values are mutable containers. In-place edits to these (obj.meta["k"] = 1) do not pass through the property setter, so they are detected by comparing against a snapshot instead.

[:object, :array].freeze
BASE =

These are the base mappings of the remote field name types.

{ objectId: :string, createdAt: :date, updatedAt: :date, ACL: :acl }.freeze
BASE_KEYS =

The list of properties that are part of all objects

[:id, :created_at, :updated_at].freeze
PROTECTED_MASS_ASSIGNMENT_KEYS =

Attribute names refused on the mass-assignment path (Parse::Object#attributes= and apply_attributes! with dirty_track: true). Internal hydration from server responses uses dirty_track: false and is unaffected, so server-issued sessionTokens etc. still flow through during decoding.

The list intentionally covers ONLY server-managed and security- internal fields. User-facing properties like acl and objectId are deliberately omitted because constructor calls like Document.new(acl: my_acl) are legitimate developer code. Rails applications receiving form input should use StrongParameters (params.permit(...)) to filter attacker-controlled keys before passing the hash to Model.new or attributes=.

%w[
  sessionToken session_token
  roles _rperm _wperm
  _hashed_password _password_history
  authData _auth_data auth_data
  className __type
  createdAt created_at updatedAt updated_at
].freeze
PROTECTED_INITIALIZE_KEYS =

Narrow subset of PROTECTED_MASS_ASSIGNMENT_KEYS that closes the documented authentication / authorization mass-assignment attacks (NEW-EXT-1) without breaking the legitimate "build a hydrated object" pattern (Klass.new("objectId" => id, "createdAt" => ts, "field" => …)). Applied by Parse::Object#initialize when trusted: false (the default) so caller-supplied hashes — even those bearing an objectId — cannot forge session tokens, ACL row-permissions, password hashes, OAuth auth_data, or roles.

Excluded from this narrow set on purpose:

  • createdAt / updatedAt: timestamp integrity, not a security boundary. App code commonly rehydrates cached objects via Klass.new(hash) and expects timestamps to populate.
  • className / __type: routing metadata. Parse::Object.build has its own className-mismatch guard; the in-memory value here is informational only.

The wider PROTECTED_MASS_ASSIGNMENT_KEYS list still applies to Parse::Object#attributes= and explicit apply_attributes!(dirty_track: true) calls, where Rails-form input is the expected source and timestamp forgery is also undesirable.

%w[
  sessionToken session_token
  roles _rperm _wperm
  _hashed_password _password_history
  authData _auth_data auth_data
].freeze
BASE_FIELD_MAP =

Default hash map of local attribute name to remote column name

{ id: :objectId, created_at: :createdAt, updated_at: :updatedAt, acl: :ACL }.freeze
CORE_FIELDS =

The delete operation hash.

{ id: :string, created_at: :date, updated_at: :date, acl: :acl }.freeze
DELETE_OP =

The delete operation hash.

{ "__op" => "Delete" }.freeze
BOOLEAN_CASTER =

Shared stateless boolean caster used by #format_value. One instance for the process lifetime — cast only consults a frozen FALSE_VALUES set, so reuse is thread-safe.

ActiveModel::Type::Boolean.new.freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.typecast_float(val) ⇒ Float?

Cast a value for a :float property.

  • nil and blank Strings become nil.
  • Numerics convert with to_f; numeric Strings with Float().
  • true/false, non-numeric Strings, NaN and Infinity raise. JSON has no NaN or Infinity, so those were serialized as null, which Parse Server treats as clearing the column.

Parameters:

  • val (Object) —

    the value to cast.

Returns:

  • (Float, nil)

Raises:



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/parse/model/core/properties.rb', line 136

def self.typecast_float(val)
  num = case val
        when nil then return nil
        when true, false
          raise TypecastError, "cannot cast boolean #{val.inspect} to a Float"
        when Numeric
          begin
            val.to_f
          rescue StandardError
            raise TypecastError, "cannot cast #{val.inspect} to a Float"
          end
        when String
          str = val.strip
          return nil if str.empty?
          unless NUMBER_STRING_FORMAT.match?(str)
            raise TypecastError, "cannot cast #{val.inspect} to a Float"
          end
          Float(str)
        else
          return typecast_float(val.to_str) if val.respond_to?(:to_str)
          raise TypecastError, "cannot cast #{val.class} to a Float" unless val.respond_to?(:to_f)
          val.to_f
        end
  unless num.is_a?(Float) && num.finite?
    raise TypecastError, "cannot store non-finite #{num.inspect} (JSON would send it as null)"
  end
  num
end

.typecast_integer(val) ⇒ Integer?

Cast a value for an :integer property.

  • nil and blank Strings become nil (a blank form field clears the column).
  • Integers pass through; Floats and other Numerics truncate with to_i.
  • Strings must be a decimal literal with an integral value: "5", "5.0" and "1e3" cast, while "1.5" and "abc" are refused rather than silently becoming 1 or 0.
  • true/false, NaN, Infinity and values with no numeric meaning raise.

Parameters:

  • val (Object) —

    the value to cast.

Returns:

  • (Integer, nil)

Raises:

  • (TypecastError) —

    when the value cannot be represented as an Integer.



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/parse/model/core/properties.rb', line 91

def self.typecast_integer(val)
  case val
  when nil then nil
  when true, false
    raise TypecastError, "cannot cast boolean #{val.inspect} to an Integer"
  when Integer then val
  when Float
    raise TypecastError, "cannot cast #{val.inspect} to an Integer" unless val.finite?
    val.to_i
  when String
    str = val.strip
    return nil if str.empty?
    unless NUMBER_STRING_FORMAT.match?(str)
      raise TypecastError, "cannot cast #{val.inspect} to an Integer"
    end
    return Integer(str, 10) unless str.match?(/[.eE]/)
    num = Float(str)
    unless num.finite? && num == num.floor
      raise TypecastError, "cannot cast #{val.inspect} to an Integer without losing its fractional part"
    end
    num.to_i
  when Numeric
    begin
      val.to_i
    rescue FloatDomainError, RangeError, NoMethodError
      raise TypecastError, "cannot cast #{val.inspect} to an Integer"
    end
  else
    return typecast_integer(val.to_str) if val.respond_to?(:to_str)
    raise TypecastError, "cannot cast #{val.class} to an Integer" unless val.respond_to?(:to_i)
    val.to_i
  end
end

.typecast_number(val) ⇒ Integer, ...

Cast a value for a :number property. Parse's Number column holds both integral and fractional values, so the cast keeps whichever the value is: an Integer when it has no fractional part (5, 5.0, "5.0", BigDecimal("5")) and a Float otherwise (4.75, "4.5"). Blank values and values that are not numeric become nil. Non-finite floats (NaN, Infinity) are kept as Floats.

Parameters:

  • val (Object) —

    the value to cast.

Returns:

  • (Integer, Float, nil)


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/parse/model/core/properties.rb', line 35

def self.typecast_number(val)
  case val
  when nil, true, false
    nil
  when Integer
    val
  when Float
    integral_or_float(val)
  when String
    str = val.strip
    return nil unless NUMBER_STRING_FORMAT.match?(str)
    str.match?(/[.eE]/) ? integral_or_float(Float(str)) : Integer(str, 10)
  when Numeric
    # BigDecimal, Rational and other Numeric types: compare against the
    # truncated value so an integral BigDecimal stays exact.
    begin
      float = val.to_f
      return float unless float.finite?
      val == val.truncate ? val.truncate.to_i : float
    rescue StandardError
      nil
    end
  else
    val.respond_to?(:to_str) ? typecast_number(val.to_str) : nil
  end
end

.typecast_number!(val) ⇒ Integer, ...

Strict variant of typecast_number used by property assignment: nil and blank Strings become nil, while values typecast_number would turn into nil (booleans, non-numeric Strings) and non-finite Floats raise instead of being sent as a Delete or a JSON null.

Parameters:

  • val (Object) —

    the value to cast.

Returns:

  • (Integer, Float, nil)

Raises:



172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/parse/model/core/properties.rb', line 172

def self.typecast_number!(val)
  return nil if val.nil? || (val.is_a?(String) && val.strip.empty?)
  if val == true || val == false
    raise TypecastError, "cannot cast boolean #{val.inspect} to a Number"
  end
  num = typecast_number(val)
  raise TypecastError, "cannot cast #{val.inspect} to a Number" if num.nil?
  if num.is_a?(Float) && !num.finite?
    raise TypecastError, "cannot store non-finite #{num.inspect} (JSON would send it as null)"
  end
  num
end

Instance Method Details

#apply_attributes!(hash, dirty_track: false, filter_protected: nil, protected_set: nil) ⇒ Hash

support for setting a hash of attributes on the object with a given dirty tracking value if dirty_track: is set to false (default), attributes are set without dirty tracking. Allos mass assignment of properties with a provided hash.

Parameters:

  • hash (Hash) —

    the hash matching the property field names.

  • dirty_track (Boolean) (defaults to: false) —

    whether dirty tracking be enabled. When true, permission-sensitive keys (PROTECTED_MASS_ASSIGNMENT_KEYS) are skipped by default so attacker-controlled params cannot overwrite acl/roles/sessionToken/etc. Set explicitly via the typed property writers when the caller is trusted.

  • filter_protected (Boolean, nil) (defaults to: nil) —

    whether to filter out PROTECTED_MASS_ASSIGNMENT_KEYS. Defaults to dirty_track for backwards-compat (the historical coupling). Callers can pass true explicitly to filter even on the trusted hydration path (used by Object#initialize when constructed with trusted: false but an objectId is in the hash). false explicitly preserves the legacy "server response" semantics.

  • protected_set (Array<String>, nil) (defaults to: nil) —

    override which key list to filter when filter_protected is true. Defaults to the wider PROTECTED_MASS_ASSIGNMENT_KEYS. Object#initialize passes PROTECTED_INITIALIZE_KEYS here to allow legitimate hydration patterns (Klass.new("objectId" => …, "createdAt" => …)) while still refusing security-critical forgeries (sessionToken, _rperm, authData, …).

Returns:



1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
# File 'lib/parse/model/core/properties.rb', line 1026

def apply_attributes!(hash, dirty_track: false, filter_protected: nil, protected_set: nil)
  return unless hash.is_a?(Hash)

  filter_protected = dirty_track if filter_protected.nil?
  protected_set ||= Parse::Properties::PROTECTED_MASS_ASSIGNMENT_KEYS
  protected_keys = filter_protected ? protected_set : nil
  # Internal hydration path lifts objectId out of the response hash. The
  # mass-assignment path must not, or attacker-controlled params can
  # overwrite the primary key of an in-memory object.
  unless dirty_track
    @id ||= hash[Parse::Model::ID] || hash[Parse::Model::OBJECT_ID] || hash[:objectId]
  end
  hash.each do |key, value|
    next if protected_keys && protected_keys.include?(key.to_s)
    method = "#{key}_set_attribute!".freeze
    send(method, value, dirty_track) if respond_to?(method)
  end
end

#attribute_changed?(attr_name, **options) ⇒ Boolean

Returns:

  • (Boolean)

See Also:

  • ActiveModel::Dirty#attribute_changed?


1185
1186
1187
1188
# File 'lib/parse/model/core/properties.rb', line 1185

def attribute_changed?(attr_name, **options)
  _detect_in_place_changes!
  super
end

#attribute_changes? ⇒ Boolean

Returns true if any of the attributes have changed.

Returns:

  • (Boolean) —

    true if any of the attributes have changed.



1250
1251
1252
1253
1254
# File 'lib/parse/model/core/properties.rb', line 1250

def attribute_changes?
  changed.any? do |key|
    fields[key.to_sym].present?
  end
end

#attribute_updates(include_all = false) ⇒ Hash

Returns a hash of attributes for properties that have changed. This will not include any of the base attributes (ex. id, created_at, etc). This method helps generate the change payload that will be sent when saving objects to Parse.

Parameters:

  • include_all (Boolean) (defaults to: false) —

    whether to include all BASE_KEYS attributes.

Returns:



1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
# File 'lib/parse/model/core/properties.rb', line 1220

def attribute_updates(include_all = false)
  # TODO: Replace this algorithm with reduce()
  h = {}
  changed.each do |key|
    key = key.to_sym
    next if include_all == false && Parse::Properties::BASE_KEYS.include?(key)
    next unless fields[key].present?
    remote_field = self.field_map[key] || key
    h[remote_field] = send key
    h[remote_field] = { __op: :Delete } if h[remote_field].nil?
    # in the case that the field is a Parse object, generate a pointer
    # if it is a Parse::PointerCollectionProxy, then make sure we get a list of pointers.
    h[remote_field] = h[remote_field].parse_pointers if h[remote_field].is_a?(Parse::PointerCollectionProxy)
    # For regular CollectionProxy arrays containing Parse objects, convert to pointers for storage
    # Nested times are encoded as Parse Dates first, since as_json would
    # turn them into plain ISO-8601 Strings.
    if h[remote_field].is_a?(Parse::CollectionProxy) && !h[remote_field].is_a?(Parse::PointerCollectionProxy)
      items = Parse::Properties.encode_nested_dates(h[remote_field].to_a)
      h[remote_field] = Parse::CollectionProxy.new(items).as_json(pointers_only: true)
    end
    h[remote_field] = h[remote_field].pointer if h[remote_field].respond_to?(:pointer)
    # Times nested inside arrays and objects are sent as Parse Dates.
    if MUTABLE_TRACKED_TYPES.include?(fields[key]) && (h[remote_field].is_a?(Array) || h[remote_field].is_a?(Hash))
      h[remote_field] = Parse::Properties.encode_nested_dates(h[remote_field])
    end
  end
  h
end

#attributes ⇒ Hash

TODO: We can optimize

Returns:

  • (Hash) —

    returns the list of property attributes for this class.



997
998
999
# File 'lib/parse/model/core/properties.rb', line 997

def attributes
  { __type: :string, :className => :string }.merge!(self.class.attributes)
end

#attributes=(hash) ⇒ Hash

Supports mass assignment of attributes

Returns:



1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
# File 'lib/parse/model/core/properties.rb', line 1047

def attributes=(hash)
  return unless hash.is_a?(Hash)
  # `acl`/`ACL` is still accepted here (a user-facing property), but
  # mass-assigning an ACL from a caller-supplied hash — e.g. a Rails
  # controller doing `record.attributes = params` without
  # StrongParameters — lets an attacker grant themselves write by
  # sending `{"ACL" => {"*" => {"write" => true}}}`. Warn (once) so the
  # foot-gun is visible; callers should set ACL via the explicit
  # `obj.acl =` setter. The constructor path (`Klass.new(acl:)`) calls
  # apply_attributes! directly and is intentionally not warned.
  if hash.key?("ACL") || hash.key?("acl") || hash.key?(:ACL) || hash.key?(:acl)
    Parse::Properties.warn_acl_mass_assignment_once!
  end
  # - [:id, :objectId]
  # only overwrite @id if it hasn't been set.
  apply_attributes!(hash, dirty_track: true)
end

#changed ⇒ Array<String>

Returns changed attribute names, including :object and :array properties edited in place.

Returns:

  • (Array<String>) —

    changed attribute names, including :object and :array properties edited in place.



1167
1168
1169
1170
# File 'lib/parse/model/core/properties.rb', line 1167

def changed
  _detect_in_place_changes!
  super
end

#changed_attributes ⇒ ActiveSupport::HashWithIndifferentAccess

Returns see ActiveModel::Dirty#changed_attributes.

Returns:

  • (ActiveSupport::HashWithIndifferentAccess) —

    see ActiveModel::Dirty#changed_attributes.



1179
1180
1181
1182
# File 'lib/parse/model/core/properties.rb', line 1179

def changed_attributes
  _detect_in_place_changes!
  super
end

#changes ⇒ ActiveSupport::HashWithIndifferentAccess

Returns see ActiveModel::Dirty#changes.

Returns:

  • (ActiveSupport::HashWithIndifferentAccess) —

    see ActiveModel::Dirty#changes.



1173
1174
1175
1176
# File 'lib/parse/model/core/properties.rb', line 1173

def changes
  _detect_in_place_changes!
  super
end

#changes_applied ⇒ Object

Clears dirty tracking and retakes the in-place baselines from the current values. See ActiveModel::Dirty#changes_applied.



1192
1193
1194
1195
# File 'lib/parse/model/core/properties.rb', line 1192

def changes_applied
  super
  _reset_mutable_snapshots!
end

#clear_changes_information ⇒ Object

Clears dirty tracking and retakes the in-place baselines from the current values. See ActiveModel::Dirty#clear_changes_information.



1199
1200
1201
1202
# File 'lib/parse/model/core/properties.rb', line 1199

def clear_changes_information
  super
  _reset_mutable_snapshots!
end

#field_map ⇒ Hash

Returns a hash mapping of all property fields and their types.

Returns:

  • (Hash) —

    a hash mapping of all property fields and their types.



986
987
988
# File 'lib/parse/model/core/properties.rb', line 986

def field_map
  self.class.field_map
end

#fields(type = nil) ⇒ Object

Returns the list of fields

Returns:

  • returns the list of fields



991
992
993
# File 'lib/parse/model/core/properties.rb', line 991

def fields(type = nil)
  self.class.fields(type)
end

#format_operation(key, val, data_type) ⇒ Object

Returns a formatted value based on the operation hash and data_type of the property. For some values in Parse, they are specified as operation hashes which could include Add, Remove, Delete, AddUnique and Increment.

Parameters:

  • key (Symbol) —

    the name of the property

  • val (Hash) —

    the Parse operation hash value.

  • data_type (Symbol) —

    The data type of the property.

Returns:



1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
# File 'lib/parse/model/core/properties.rb', line 1263

def format_operation(key, val, data_type)
  return val unless val.is_a?(Hash) && val["__op"].present?
  op = val["__op"]
  ivar = :"@#{key}"
  #handles delete case otherwise 'null' shows up in column
  if "Delete" == op
    val = nil
  elsif "Add" == op && data_type == :array
    val = (instance_variable_get(ivar) || []).to_a + (val["objects"] || [])
  elsif "Remove" == op && data_type == :array
    val = (instance_variable_get(ivar) || []).to_a - (val["objects"] || [])
  elsif "AddUnique" == op && data_type == :array
    objects = (val["objects"] || []).uniq
    original_items = (instance_variable_get(ivar) || []).to_a
    objects.reject! { |r| original_items.include?(r) }
    val = original_items + objects
  elsif "Increment" == op && NUMERIC_TYPES.include?(data_type)
    # for operations that increment by a certain amount, they come as a hash.
    # The sum is cast to the property type by format_value afterwards.
    current = instance_variable_get(ivar)
    current = 0 unless current.is_a?(Numeric)
    amount = val["amount"]
    amount = 0 unless amount.is_a?(Numeric)
    val = current + amount
  end
  val
end

#format_value(key, val, data_type = nil) ⇒ Object

this method takes an input value and transforms it to the proper local format depending on the data type that was set for a particular property key. Return the internal representation of a property value for a given data type.

Parameters:

  • key (Symbol) —

    the name of the property

  • val (Object) —

    the value to format.

  • data_type (Symbol) (defaults to: nil) —

    provide a hint to the data_type of this value.

Returns:



1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
# File 'lib/parse/model/core/properties.rb', line 1298

def format_value(key, val, data_type = nil)
  # if data_type wasn't passed, then get the data_type from the fields hash
  data_type ||= self.fields[key]

  val = format_operation(key, val, data_type)

  case data_type
  when :object
    # Copy so the property never shares containers with the caller's
    # hash: an edit through one must not silently change the other.
    val = Parse::Properties.deep_copy_value(val).with_indifferent_access if val.is_a?(Hash)
  when :array
    # All "array" types use a collection proxy. nil elements are kept:
    # dropping them shifted every later element to a new index.
    val = val.to_a if val.is_a?(Parse::CollectionProxy) #all objects must be in array form
    val = if val.nil?
        []
      elsif val.is_a?(Array)
        # Copy so the proxy does not alias the caller's array (or another
        # proxy's backing store).
        Parse::Properties.deep_copy_value(val)
      else
        [val]
      end
    val = Parse::CollectionProxy.new val, delegate: self, key: key
  when :geopoint
    val = Parse::GeoPoint.new(val) unless val.blank?
  when :polygon
    val = Parse::Polygon.new(val) unless val.blank?
  when :file
    if val.is_a?(Hash) && val["__type"] == "File"
      val = Parse::File.new(val)
    elsif !val.blank?
      val = Parse::File.new(val)
    end
  when :bytes
    if val.is_a?(Hash) && val["__type"] == "Bytes"
      val = Parse::Bytes.new(val["base64"] || val[:base64])
    elsif !val.blank?
      val = Parse::Bytes.new(val)
    end
  when :integer
    val = _typecast_for(key) { Parse::Properties.typecast_integer(val) }
  when :boolean
    # Coerce via ActiveModel's boolean caster rather than Ruby
    # truthiness. Plain `val ? true : false` treats every non-nil,
    # non-false object as true, so the strings "false", "0", and "off"
    # — exactly what arrives on the Rails-form / query-string ingestion
    # path — would coerce to `true` and silently flip a boolean the
    # wrong way (e.g. an `archived` or admin gate). ActiveModel maps the
    # string forms ("false"/"0"/"f"/"off"/"") to false/nil. Parse wire
    # JSON already sends real booleans, which pass through unchanged.
    # "no" and "n" are also false (ActiveModel would cast them to true).
    val = if val.nil?
        nil
      elsif val.is_a?(String) && EXTRA_FALSE_STRINGS.include?(val.strip.downcase)
        false
      else
        BOOLEAN_CASTER.cast(val)
      end
  when :string
    # Every non-nil value becomes a String (false becomes "false", as
    # true already became "true"). Arrays and Hashes are refused: their
    # String form is Ruby inspect output, not data.
    if val.is_a?(Array) || val.is_a?(Hash) || val.is_a?(Parse::CollectionProxy)
      _typecast_for(key) { raise TypecastError, "cannot store a #{val.class} in a String property" }
    elsif !val.nil? && !val.is_a?(String)
      val = val.to_s
    end
  when :float
    val = _typecast_for(key) { Parse::Properties.typecast_float(val) }
  when :number
    val = _typecast_for(key) { Parse::Properties.typecast_number!(val) }
  when :acl
    # ACL types go through a special conversion
    val = ACL.typecast(val, self)
  when :date
    # if it respond to parse_date, then use that as the conversion.
    if val.respond_to?(:parse_date) && val.is_a?(Parse::Date) == false
      val = val.parse_date
      # if the value is a hash, then it may be the Parse hash format for an iso date.
    elsif val.is_a?(Hash) # val.respond_to?(:iso8601)
      iso_val = (val["iso"] || val[:iso]).to_s.strip.presence
      val = iso_val ? Parse::Date.parse(iso_val) : nil
    elsif val.is_a?(String)
      # if it's a string, try parsing the date
      val = (stripped = val.strip).present? ? Parse::Date.parse(stripped) : nil
    elsif !val.nil? && !val.is_a?(Parse::Date)
      # A Numeric (or any other value) was previously stored raw and sent
      # as a plain number. Refuse it: an epoch value is ambiguous
      # (seconds or milliseconds), so convert with Time.at explicitly.
      _typecast_for(key) do
        raise TypecastError, "cannot cast #{val.class} to a Date; pass a Time, DateTime, " \
                             "Parse::Date or ISO-8601 String"
      end
    end
  when :timezone
    val = Parse::TimeZone.new(val) if val.present?
  when :phone
    val = Parse::Phone.new(val) if val.present?
  when :email
    val = Parse::Email.new(val) if val.present?
  when :vector
    # nil/blank → unset; coerce Arrays (and pass-through Parse::Vector)
    # to a Parse::Vector, which validates that every element is a
    # finite Numeric. Dimension mismatch is reported via
    # validates_each so callers can rescue ActiveModel::ValidationError
    # at save time rather than at every assignment; raising here
    # would break partial hydration where the dimension class-level
    # declaration may not yet be loaded.
    if val.nil?
      val = nil
    elsif val.is_a?(Parse::Vector)
      val = val
    elsif val.is_a?(Array)
      val = Parse::Vector.new(val)
    else
      raise ArgumentError,
            "Property #{self.class}##{key} :vector requires an Array or Parse::Vector " \
            "(got #{val.class})."
    end
  else
    # You can provide a specific class instead of a symbol format
    if data_type.respond_to?(:typecast)
      val = data_type.typecast(val)
    else
      warn "Property :#{key}: :#{data_type} has no valid data type"
      val = val #default
    end
  end
  val
end