Reputation: 73
guys! I'm looking for the best approach the situation, I'm describing below.
There is the page with two different modes. e.g. Grid and List mode. Both of modes need two different representations.
So, currently, I've one route action and flag parameter (smth like 'preview') to detect which serializer needs to apply.
I suppose that it's not the best way to do it. Let's imagine. In the future, there will be two more different view modes. So, in some way, I need to manage all those ways.
Thanks!
Upvotes: 1
Views: 631
Reputation: 3860
I hope you can do this using const_get to load the serializer class that you want dynamically by following a simple conventions.
Consider you may have two serializers for mode and grid. Create these under a same namespace called Mode like
serializers/mode/grid_serializer.rb(Mode::GridSerializer)
serializer/mode/list_serializer.rb(Mode::ListSerializer)
In controller action you receive your params preview value "grid"
, You can load serializer class by doing
serializer = Mode.const_get(params["preview"].camelcase + "Serializer")
I hope this helps. Thanks.
Upvotes: 0
Reputation: 298
You can use guard style conditions or even move them later to a separate method. That is totally ok in case you doubt.
serialize = SerializerOne if a
serialize = SerializerTwo if b
...
serialize = SerializerN if n
render json: result, each_serializer: serialize
Upvotes: 1