Search code examples
ruby-on-rails-4active-model-serializers

Pass serializer: a String


In Active Model Serializers you can use a different Serializer by doing respond with resource, serializer: ViewContractsSerializer. The issue is that I want that to be dynamic by using serializer: "View#{resource_name}Serializer" and that does not work because it is a string. If i do serializer: eval("View#{resource_name}Serializer") it works of course, but I know that you should not use eval in production code.


Solution

  • Rails has a helpful constantize method that can do what you want:

    respond_with resource,
      serializer: "View#{resource_name}Serializer".constantize