mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-22 22:06:50 +00:00
trying to get styling correct added changelog entry, link to guide, and fixed indentation
1.1 KiB
1.1 KiB
How to serialize a Plain-Old Ruby Object (PORO)
When you are first getting started with ActiveModelSerializers, it may seem only ActiveRecord::Base objects can be serializable, but pretty much any object can be serializable with ActiveModelSerializers. Here is an example of a PORO that is serializable:
# my_model.rb
class MyModel
alias :read_attribute_for_serialization :send
attr_accessor :id, :name, :level
def initialize(attributes)
@id = attributes[:id]
@name = attributes[:name]
@level = attributes[:level]
end
def self.model_name
@_model_name ||= ActiveModel::Name.new(self)
end
end
Fortunately, ActiveModelSerializers provides a ActiveModelSerializers::Model which you can use in production code that will make your PORO a lot cleaner. The above code now becomes:
# my_model.rb
class MyModel < ActiveModelSerializers::Model
attr_accessor :id, :name, :level
end
The default serializer would be MyModelSerializer.