Home > front end >  Does Serialization is same in Ruby as in other language
Does Serialization is same in Ruby as in other language

Time:11-14

I have started building application in Ruby and come to know the gem serialzer, but I am confused as I am from python background in that serialzation means to convert the response into bytes but here we simply use as attributes.

What exactly happens in Ruby with serialization?

class UserSerializer < ActiveModel::Serializer
attributes :name
end

CodePudding user response:

Serialization in Ruby generally can mean to convert any kind of object into a form that can be transmitted or stored. This broader definition is closer to the one used in computer science.

For example the built in Marshal module converts objects into a byte stream which allows them to be stored outside the currently active script and then be reconstituted. This is a form of serialization that should be instantly recognizable to a Pythonista.

In Rails specifically the term serialization is commonly used for two things:

  • Converting model data into transmission formats such as JSON (or XML back in ye olde times) to be sent across the wire to clients or other servers. Rails has simple form of serialization built in through the as_json method. This is where gems like ActiveModel::Serializers, jbuilder and the plethora of JSONAPI.org gems come into play.
  • ActiveRecord::AttributeMethods::Serialization - which is an old hack to store hashes and other types of objects in VARCHAR or TEXT type columns in the database. Rails marshals/unmarshals them as JSON or YAML on the application side which kind of sucks if you want to be able to query the data in a sensible way. While this is largely supplanted by native ARRAY and JSON/JSONB types it does still have a few legit uses such as storing encrypted data.

ActiveModel::Serializers (not to be confused with Rails built in ActiveModel::Serialization) is basically the swiss army bulldozer gem of object serialization for Rails. It consists of a pretty simple structure of serializer classes which are blueprint for turning the model into JSON. They are used in your controller to provide JSON responses.

For example that serializer could produce something like:

{
  "name": "John Doe"
}

But the actual format depends on the configuration of ActiveModel::Serializers - it can produce tons of different output formats like "flat objects" or JSONAPI.org:

{
  "type": "user",
  "id": "1",
  "attributes": {
    "name": "John Doe",
  }
}

CodePudding user response:

rails do the same but what it faciliates the both like you can either convert it in binary as well as human readable.

  • Related