Volodymyr O
Volodymyr O

Reputation: 73

Rails Active Model serialize best way to apply different serializes for one action

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

Answers (2)

Narasimha Reddy - Geeker
Narasimha Reddy - Geeker

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

Denis Romanovsky
Denis Romanovsky

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

Related Questions