Search code examples
ruby-on-railswebsocketactive-model-serializers

Is it possible to use ActiveModel::Serializers outside of Rails controller?


I'm using websocket-rails gem for web-sockets and I would like to use ActiveModel::Serializers for creating JSON payload for web-socket message. Is it possible to use serializer without using render in controller?


Solution

  • After looking into source code, I found answer I was looking for. You can use AMS by explicitly instantiating serializer: ConversationSerializer.new(Conversation.last).as_json

    for collection: ActiveModel::Serializer::CollectionSerializer.new(Conversation.all, serializer: ConversationSerializer).as_json