跳至内容 跳至搜索

Active Model 值类型

所有属性类型的基类。此类也用作未指定类型的属性的默认类型。

方法
#
A
C
D
E
H
N
S
T
包含的模块

属性

[R] limit
[R] precision
[R] scale

类公共方法

new(precision: nil, limit: nil, scale: nil)

使用三个基本配置设置初始化类型:精度、限制和比例。 Value 基类未定义这些设置的行为。它仅将它们用于相等比较和哈希键生成。

# File activemodel/lib/active_model/type/value.rb, line 17
def initialize(precision: nil, limit: nil, scale: nil)
  super()
  @precision = precision
  @scale = scale
  @limit = limit
end

实例公共方法

==(other)

也称为:eql?
# File activemodel/lib/active_model/type/value.rb, line 121
def ==(other)
  self.class == other.class &&
    precision == other.precision &&
    scale == other.scale &&
    limit == other.limit
end

as_json(*)

# File activemodel/lib/active_model/type/value.rb, line 144
def as_json(*)
  raise NoMethodError
end

assert_valid_value(_)

# File activemodel/lib/active_model/type/value.rb, line 133
def assert_valid_value(_)
end

cast(value)

Type 将用户输入(例如来自设置器)的值转换为相应类型。此值可能是来自表单生成器的字符串,也可能是传递给设置器的 Ruby 对象。目前无法区分其来源。

此方法的返回值将从 ActiveRecord::AttributeMethods::Read#read_attribute 返回。另请参阅:Value#cast_value.

value 原始输入,如提供给属性设置器。

# File activemodel/lib/active_model/type/value.rb, line 57
def cast(value)
  cast_value(value) unless value.nil?
end

changed?(old_value, new_value, _new_value_before_type_cast)

确定值是否已更改以进行脏检查。old_valuenew_value 将始终进行类型转换。类型不需要覆盖此方法。

# File activemodel/lib/active_model/type/value.rb, line 84
def changed?(old_value, new_value, _new_value_before_type_cast)
  old_value != new_value
end

changed_in_place?(raw_old_value, new_value)

确定可变值自读取后是否已修改。默认情况下返回 false。如果您的类型返回可以被修改的对象,您应该覆盖此方法。您需要:

  • new_value 传递给 Value#serialize 并将其与 raw_old_value 进行比较

raw_old_value 原始值,在传递给 deserialize 之前。

new_value 当前值,在类型转换后。

# File activemodel/lib/active_model/type/value.rb, line 105
def changed_in_place?(raw_old_value, new_value)
  false
end

deserialize(value)

将值从数据库输入转换为相应的 Ruby 类型。此方法的返回值将从 ActiveRecord::AttributeMethods::Read#read_attribute 返回。默认实现只是调用 Value#cast.

value 原始输入,如从数据库提供。

# File activemodel/lib/active_model/type/value.rb, line 43
def deserialize(value)
  cast(value)
end

eql?(other)

别名:==

hash()

# File activemodel/lib/active_model/type/value.rb, line 129
def hash
  [self.class, precision, scale, limit].hash
end

serializable?(value)

如果此类型可以将value转换为数据库可用的类型,则返回 true。例如,布尔类型如果 value 参数是 Ruby 布尔值,则可以返回true,但如果 value 参数是其他对象,则可能返回false

# File activemodel/lib/active_model/type/value.rb, line 28
def serializable?(value)
  true
end

serialize(value)

将值从 ruby 类型转换为数据库可以理解的类型。此方法返回的值应为StringNumericDateTimeSymboltruefalsenil

# File activemodel/lib/active_model/type/value.rb, line 65
def serialize(value)
  value
end

type()

将唯一的类型名称作为Symbol返回。子类应覆盖此方法。

# File activemodel/lib/active_model/type/value.rb, line 34
def type
end

实例私有方法

cast_value(value)

对于不需要为用户和数据库输入分别进行类型转换行为的类型,这是一个便捷方法。由Value#cast调用,用于除nil以外的值。

# File activemodel/lib/active_model/type/value.rb, line 152
def cast_value(value) # :doc:
  value
end