Support mappable classes in query_one and query_all methods

This commit is contained in:
Santiago Palladino 2016-07-04 12:46:45 -03:00
parent 99352d9d2d
commit 9ca0b19d9e
3 changed files with 29 additions and 0 deletions

View file

@ -1,5 +1,8 @@
module DB
# Empty module used for marking a class as supporting DB:Mapping
module Mappable; end
# The `DB.mapping` macro defines how an object is built from a DB::ResultSet.
#
# It takes hash literal as argument, in which attributes and types are defined.
@ -56,6 +59,8 @@ module DB
#
# This macro also declares instance variables of the types given in the mapping.
macro mapping(properties, strict = true)
include DB::Mappable
{% for key, value in properties %}
{% properties[key] = {type: value} unless value.is_a?(HashLiteral) || value.is_a?(NamedTupleLiteral) %}
{% end %}

View file

@ -64,6 +64,11 @@ module DB
# Reads the next column value
abstract def read
# Reads the next columns and maps them to a class
def read(type : DB::Mappable.class)
type.new(self)
end
# Reads the next column value as a **type**
def read(type : T.class) : T
read.as(T)