ActiveRecord_Relation serialization
nesaulov opened this issue · 8 comments
Right now objects that are created from methods that return ActiveRecord_Relation
(like #where
) can not be surrealized:
User.where(id: 3).surrealize
# => NoMethodError: undefined method `surrealize' for #<User::ActiveRecord_Relation:0x007f90ae569758>
We need to have some kind of schema delegation to the initial object here.
I guess we have two ways here:
- Monkey-patch
ActiveRecord_Relation
so it has#surrealize
on an instance. - Force users to use
Surrealist#surrealize(instance)
directly.
I personally prefer second option, because of absence of monkey-patching and because ActiveRecord
is not the only ORM out there, so we will have to monkey-patch a lot of things.
Could we just map back the surrealization of each element:
# something like this 🤷🤷 ¯\_(ツ)_/¯
def surrealize(instance:, camelize:, include_root:)
return instance.map { |i| surrealize(i,camelize, include_root) } if instance.respond_to?(:each) #
::JSON.dump(build_schema(instance: instance, camelize: camelize, include_root: include_root))
end
I think this produces similar behaviour as ActiveModel::Serializer.
@AlessandroMinali yeah, you are right, it's a third option and it looks alright. I'll think about it for a while.
Actually, there is the same downside as in the first option - we'll have to monkey-patch Enumerable
and else, because otherwise NoMehtodError
is thrown:
User.where(id: 3).surrealize
# => NoMethodError: undefined method `surrealize' for #<User::ActiveRecord_Relation:0x007f90ae569758>
Hmm, right.
I guess a simple solution is to introduce a new method like mentioned in the other issue which is just a wrapper to call"
return instance.map { |i| surrealize(i,camelize, include_root) } if instance.respond_to?(:each) #
Would be nice if it just worked
though without a separate method.
Here are monkey-patch attempt and a #surrealize_collection methods WIPs to compare.
Both have specs for AR, ROM, Datamapper and Sequel.
thanks, @AlessandroMinali! I think #surrealize_collection
way is much better than monkey-patching, so we can continue to work on that one. Am I right that the API you are planning to introduce is Surrealist.surrealize_collection(collection)
?
Yes, that's correct @nesaulov, with the ability to specific camelize and include root etc. if they so choose.