{"id":15692019,"url":"https://github.com/gsamokovarov/serializr","last_synced_at":"2025-05-07T23:47:36.858Z","repository":{"id":56895098,"uuid":"70242686","full_name":"gsamokovarov/serializr","owner":"gsamokovarov","description":"Serializr is a library for creating canonical JSON representation of objects for your RESTful APIs.","archived":false,"fork":false,"pushed_at":"2018-03-04T16:24:35.000Z","size":34,"stargazers_count":7,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-15T23:09:33.790Z","etag":null,"topics":["json-representation","rails","ruby","serializer"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gsamokovarov.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-10-07T12:01:26.000Z","updated_at":"2019-07-15T23:26:44.000Z","dependencies_parsed_at":"2022-08-20T17:10:19.092Z","dependency_job_id":null,"html_url":"https://github.com/gsamokovarov/serializr","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gsamokovarov%2Fserializr","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gsamokovarov%2Fserializr/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gsamokovarov%2Fserializr/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gsamokovarov%2Fserializr/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gsamokovarov","download_url":"https://codeload.github.com/gsamokovarov/serializr/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252973622,"owners_count":21834105,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["json-representation","rails","ruby","serializer"],"created_at":"2024-10-03T18:27:53.004Z","updated_at":"2025-05-07T23:47:36.843Z","avatar_url":"https://github.com/gsamokovarov.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Serializr\n\nSerializr is a library for creating canonical JSON representation of objects\nfor your RESTful APIs.\n\nThink of the serializers as the view layer of your application. They are not\nthe only JSON representation of an object, but they are _the_ representation\nyou wanna show to the API.\n\n## Installation\n\nAdd this line to your application's Gemfile:\n\n```ruby\ngem 'serializr'\n```\n\n## Usage\n\nUsing the serializr library is pretty simple. To generate your first\nserializer, execute:\n\n    $ rails generate serializr User id name email\n\nThe output should hint that the generator created two files:\n\n    create  app/serializers/application_serializer.rb\n    create  app/serializers/user_serializer.rb\n\nThe `app/serializers/user_serializer.rb` file should contain:\n\n```ruby\nclass UserSerializer \u003c ApplicationSerializer\n  attributes :id, :name, :email\nend\n```\n\nThis says: expect the object to be serialized to respond to `#id`, `#name` and\n`#email` and show the resulting JSON as:\n\n```json\n{\n  \"id\": 42,\n  \"name\": \"John Doe\",\n  \"email\": \"john@nsa.gov\"\n}\n```\n\nOh, wait... Your users don't respond to `#name`?\n\n```ruby\nclass UserSerializer \u003c ApplicationSerializer\n  attributes :id, :name, :email\n\n  def name\n    \"#{object.first_name} #{object.last_name}\"\n  end\nend\n```\n\nThat's fine. Your serializers can render fields your object don't respond to.\n\nNow, to render the JSON object, you need to say the following in your\ncontroller:\n\n```ruby\nclass UsersController \u003c ApplicationController\n  def show\n    user = User.find(params[:id])\n\n    render json: user\n  end\nend\n```\n\nThe serializr library hooks itself into `ActionController::Base` or\n`ActionController::API` and it can infer the `UserSerializer` out of the `User`\nobject. You can also be explicit, in which case the inferring logic won't be\ntriggered at all.\n\n```ruby\nclass UsersController \u003c ApplicationController\n  def show\n    user = User.find(params[:id])\n\n    render json: user, serializer: UserSerializer\n  end\nend\n```\n\nYou can also render collections of objects:\n\n```ruby\nclass FriendsController \u003c ApplicationController\n  def index\n    friends = User.friends_of(params[:id])\n\n    render json: friends\n  end\nend\n```\n\nBeing explicit here may have performance benefits, as to guess the `Serializer`\nclass to use, we need to unroll the collection. The explicit usage, unarguably,\nlooks pretty awesome as well, so you can wow your friends! Which, is always\ncool, you know. 😎\n\n```ruby\nclass FriendsController \u003c ApplicationController\n  def index\n    friends = User.friends_of(params[:id])\n\n    render json: friends, serializer: UserSerializer[]\n  end\nend\n```\n\nAnd this is how you drop `Action View` off your API's, kids!\n\n### ☝️  Last Thing\n\nTo fill the API cliché, we need to go over one last file:\n`app/serializers/application_serializer.rb`. At first, it looks like this:\n\n```ruby\nclass ApplicationSerializer \u003c Serializr\nend\n```\n\nThe grown ups call it [Layer\nSupertype](http://martinfowler.com/eaaCatalog/layerSupertype.html). We'll call\nit that thing that looks like `ApplicationController` and serves the same\npurpose, but for the serializers, not the controllers. You can use it to put\ncommon utilities shared by all the serializers.\n\nFor example:\n\n```ruby\nclass ApplicationSerializer \u003c Serializr\n  # You may need the routes helpers, so you can link between resources in your\n  # JSON responses.\n  include Rails.application.routes.url_helpers\n\n  cattr_reader :serializer_class_cache do\n    Hash.new do |hash, cls|\n      hash[cls] = \"#{cls}Serializer\".constantize\n    end\n  end\n\n  # Because I'm sure you gonna ask: how do I render associations. Where are the\n  # `has_one` and `has_many` class macros?\n  #\n  # The answers is: you don't need those macros. You can use similar methods\n  # like the ones below to render the associations with plain old boring Ruby\n  # methods.\n  #\n  # class UserSerializer \u003c ApplicationSerializer\n  #   attributes :card\n  #\n  #   def card\n  #     render_one(object.credit_card)\n  #   end\n  # end\n  #\n  # No extra DSL, but still: clean, consise and flexible view code.\n  def render_one(object, serializer: nil)\n    return if object.nil?\n\n    serializer ||= serializer_class_cache[object.class]\n    serializer.new(object)\n  end\n\n  def render_many(objects, serializer: nil)\n    return [] if objects.blank?\n\n    serializer ||= serializer_class_cache[objects.first.class][]\n    serializer.new(objects)\n  end\nend\n```\n\n### ✌️  Last Thing\n\nSerializr? Really? I know. It's fine.\n\nYou can require `serializr`, you can require `serializer` as well. The\nconstants? Both of `Serializr` and `Serializer` point to the same thing. Same\nfor the generators. Use whatever your brain and 🖐 (fingers) like.\n\n## Contributing\n\nBug reports and pull requests are welcome on GitHub at\nhttps://github.com/gsamokovarov/serializr. This project is intended to be a\nsafe, welcoming space for collaboration, and contributors are expected to\nadhere to the [Contributor Covenant](http://contributor-covenant.org) code of\nconduct.\n\n## License\n\nThe gem is available as open source under the terms of the [MIT\nLicense](http://opensource.org/licenses/MIT).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgsamokovarov%2Fserializr","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgsamokovarov%2Fserializr","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgsamokovarov%2Fserializr/lists"}