-
Notifications
You must be signed in to change notification settings - Fork 88
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
Support model.from_json(JSON::Any) #221
Conversation
Unfortunately this still does not work. might be able to create a wrapper function that will instantiate multiple classes and return an array of them to replicate the class Foo < Granite::Base
adapter mysql
table_name foos
primary type_id : Int64, auto: false
field capacity : Float32
end p Array(Foo).new(JSON.parse(%([{"type_id": 1, "capacity": 69.0},{"type_id": 2, "capacity": 5.0},{"type_id": 3, "capacity": 100.0}])))
|
I refactored things to support This accounts for creating a single record from a json object, or an array of models from an array of json objects. The one con of this is that the user has to specify which it is. For example see the spec: Notice how in the first i am specifying |
{% end %} | ||
return | ||
end | ||
|
||
return @{{_name.id}} = nil if value.nil? | ||
{% if type.id == Int32.id %} | ||
@{{_name.id}} = value.is_a?(String) ? value.to_i32(strict: false) : value.is_a?(Int64) ? value.to_i32 : value.as(Int32) | ||
@{{_name.id}} = value.is_a?(JSON::Any) ? value.as_i : value.is_a?(String) ? value.to_i32(strict: false) : value.is_a?(Int64) ? value.to_i32 : value.as(Int32) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
man, this is some true ugliness on my part. Maybe someday we can figure out how to clean this up.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice addition. The json api isn't very elegant, and I think it's possible to come up with a better DSL than what from_json
provides, but I don't think it's necessary for this addition to be helpful.
@robacarp it should be clarified that the |
@Blacksmoke16 yep. Since there are two approvals, are you ready for this to merge? |
I probably should add some info to the README. I'll do that tonight and can merge it tomorrow. |
@Blacksmoke16 let me know when you are ready. |
Readme is updated. Should be good to go @drujensen |
@Blacksmoke16 thank you! |
This PR resolves #170 by including support for model.new(JSON::Any)
I just added another layer of ternary that checks of the value is of the
JSON::Any
type, if it is then use theJSON::Any
.as_x to cast it to proper type.