rom-rb / rom

Data mapping and persistence toolkit for Ruby
https://rom-rb.org
MIT License
2.08k stars 161 forks source link

Add support for defining schema types for reading data #377

Closed solnic closed 7 years ago

solnic commented 7 years ago

This extends schema DSL with the ability to define "read" type that will be used when a relation loads its tuples. By default we set this to a noop passthrough-proc but if there are any attributes with a special "read" type then we use relation's schema "relation hash" which is built from schema attributes including "read" types.

This is a last-moment addition but it turned out we can't support various custom DB types without this feature, and it was planned already for rom 3.1.0 anyway.

Here's extended schema API:

class Users < ROM::Relation[:yaml]
  schema do
    # this means that the canonical db type is a string but we want an int
    # in resulting relation tuples
    attribute :id, Types::String, read: Types::Coercible::Int
    attribute :name, Types::String
  end
end

/cc @flash-gordon @AMHOL

solnic commented 7 years ago

I should add that inferrer can be extended to infer :read types based on various criteria. Good example is jruby + sqlite which for some reason doesn't coerce date/time strings (as they are stored by sqlite) into date/time object, we can easily solve this kind of discrepancies between different rubies/dbs/drivers :) /cc @cflipse