Attributes
Use cases
Structured JSON
# In some model...
attribute :my_custom_attribute, Attributes::MyCustomAttribute.new# The "bridge" between the attribute definition and the custom attribute type
class Attributes::MyCustomAttribute < ActiveRecord::Type::Json
def deserialize(value)
return value unless value.is_a?(String)
parsed = JSON.parse(value)
if parsed.blank?
return MyCustomAttribute.new
end
MyCustomAttribute.new(**parsed.symbolize_keys)
end
def serialize(value)
value&.to_json
end
endSources
Last updated