More concise JSON serialization #526
Replies: 3 comments 7 replies
-
Just thinking about this. I actually love the API we already have setup. It's setup easy to understand and use. Since we have the Now, what I think might be cool is adding class UserSerializer < BaseSerializer
needs user : User
# or whatever it would be called
serialize name, age, username, email
end That would essentially do this: class UserSerializer < BaseSerializer
def initialize(@user : User)
end
def render
{name: @user.name, age: @user.age, username: @user.username, email: @user.email}
end
end and of course, the escape hatch here would be that you can just define What are your thoughts on this? |
Beta Was this translation helpful? Give feedback.
-
@jwoertink I like the idea of adding needs. I much prefer it over initialize in most cases TBH 😆especially since you can inherit needs. I'm not as big a fan of a serialize macro because:
I think we can maybe solve this with regular methods, or potentially with a macro and really good error handling messages. What if we had something like this where it kind of crosses between your suggestion and the original method based approach? class Users::Serializer < BaseSerializer
needs include_details : Bool = false
needs user : User
def render
set({name: user.name, foo: "bar"}) # This is basically what you have today
set(:single_key, 123) # Set a single key
# Works great for conditionals
if include_details?
set(all_the_deets: true)
end
# macro for setting multiple attrs
set_attrs :email, :age, :other_thing, from: user
# expands to
set({email: user.email, age: user.age, other_thing: user.other_thing})
# Also allow setting it under another key
set_attrs :email, :age, :other_thing, from: user, key: :user
end
end Thoughts? I like this because the simple case is still there, you can see how to use conditionals pretty easily, and how to customize stuff. And it adds the And since it is all still in a regular method changing the key name for a particular method is easy: set_attrs :email, :age, from: user
set :name, "#{user.first_name} #{user.last_name}" |
Beta Was this translation helpful? Give feedback.
-
Since abstract class Lucky::Serializer
def to_json(io)
render.to_json(io)
end
end Does it make sense to transition it into a module? With this talk about adding in |
Beta Was this translation helpful? Give feedback.
-
Just an experiment for now. Not sure howmerge
would work, but I think it is a nicer API.EDIT: This is the old/original example, new proposals are in the comments!
Beta Was this translation helpful? Give feedback.
All reactions