Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add to_h and to_json to Granite::ORM::Fields #72

Merged
merged 3 commits into from
Oct 17, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions spec/granite_orm_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ require "../src/adapter/pg"
class Todo < Granite::ORM::Base
adapter pg
field name : String
field priority : Int32
timestamps
end

Expand All @@ -12,4 +13,18 @@ describe Granite::ORM::Base do
t = Todo.new(name: "Elorest")
t.name.should eq "Elorest"
end

it "should provide a to_h method" do
t = Todo.new(name: "test todo", priority: 20)
result = { "name" => "test todo", "priority" => 20, "created_at" => nil, "updated_at" => nil }

t.to_h.should eq result
end

it "should provide a to_json method" do
t = Todo.new(name: "test todo", priority: 20)
result = %({"name":"test todo","priority":20,"created_at":null,"updated_at":null})

t.to_json.should eq result
end
end
24 changes: 24 additions & 0 deletions src/granite_orm/fields.cr
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,30 @@ module Granite::ORM::Fields
return parsed_params
end

def to_h
fields = {} of String => Bool | Float32 | Float64 | Int32 | Int64 | String | Time | Nil

{% for name, type in FIELDS %}
{% if type.id == Time.id %}
fields["{{name}}"] = {{name.id}}.try(&.to_s("%F %X"))
{% elsif type.id == Slice.id %}
fields["{{name}}"] = {{name.id}}.try(&.to_s(""))
{% else %}
fields["{{name}}"] = {{name.id}}
{% end %}
{% end %}
{% if SETTINGS[:timestamps] %}
fields["created_at"] = created_at.try(&.to_s("%F %X"))
fields["updated_at"] = updated_at.try(&.to_s("%F %X"))
{% end %}

return fields
end

def to_json
to_h.to_json
end

# Cast params and set fields.
private def cast_to_field(name, value : DB::Any)
if !value.nil?
Expand Down