Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 495
Anatoliy Kukul Avatar asked Dec 05 '22 04:12

Anatoliy Kukul


2 Answers

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

like image 86
Anatoliy Kukul Avatar answered Dec 21 '22 22:12

Anatoliy Kukul


Yes, it is possible.

Let's say that you have a Product model and a p record:

# p = Product.first
ProductSerializer.new(p).to_json

Also, be aware that you may have to load the required files:

require "action_controller"
require "action_controller/serialization"
require "#{Rails.root}/app/serializers/product_serializer.rb"
like image 22
Daniel Loureiro Avatar answered Dec 21 '22 23:12

Daniel Loureiro