Serializing Non-ActiveRecord Objects
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
ActiveModelSerializers provides a ActiveModelSerializers::Model that can make your PORO a lot cleaner. Using it, the above code becomes:
# my_model.rb
class MyModel < ActiveModelSerializers::Model
attr_accessor :id, :name, :level
end
The default serializer would be MyModelSerializer.