{"id":19552785,"url":"https://github.com/ruby-grape/grape-active_model_serializers","last_synced_at":"2025-04-04T07:04:08.105Z","repository":{"id":7804442,"uuid":"9174850","full_name":"ruby-grape/grape-active_model_serializers","owner":"ruby-grape","description":"User active_model_serializers with Grape","archived":false,"fork":false,"pushed_at":"2019-08-30T21:30:50.000Z","size":144,"stargazers_count":140,"open_issues_count":9,"forks_count":69,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-03-28T06:04:46.222Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"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/ruby-grape.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-04-02T16:41:53.000Z","updated_at":"2025-03-21T01:18:45.000Z","dependencies_parsed_at":"2022-08-30T10:11:27.805Z","dependency_job_id":null,"html_url":"https://github.com/ruby-grape/grape-active_model_serializers","commit_stats":null,"previous_names":["jrhe/grape-active_model_serializers"],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ruby-grape%2Fgrape-active_model_serializers","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ruby-grape%2Fgrape-active_model_serializers/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ruby-grape%2Fgrape-active_model_serializers/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ruby-grape%2Fgrape-active_model_serializers/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ruby-grape","download_url":"https://codeload.github.com/ruby-grape/grape-active_model_serializers/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247135139,"owners_count":20889420,"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":[],"created_at":"2024-11-11T04:19:42.822Z","updated_at":"2025-04-04T07:04:08.080Z","avatar_url":"https://github.com/ruby-grape.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Grape::ActiveModelSerializers\n\nUse [active_model_serializers](https://github.com/rails-api/active_model_serializers) with [Grape](https://github.com/intridea/grape)!\n\n[![Gem Version](https://badge.fury.io/rb/grape-active_model_serializers.svg)](https://badge.fury.io/rb/grape-active_model_serializers)\n[![Build Status](https://api.travis-ci.org/ruby-grape/grape-active_model_serializers.svg)](http://travis-ci.org/ruby-grape/grape-active_model_serializers) [![Code Climate](https://codeclimate.com/github/ruby-grape/grape-active_model_serializers.svg)](https://codeclimate.com/github/ruby-grape/grape-active_model_serializers)\n\n## Installation\n\nAdd the `grape` and `grape-active_model_serializers` gems to Gemfile and run `bundle install`.\n\n```ruby\ngem 'grape-active_model_serializers'\n```\n\nSee [UPGRADING](UPGRADING.md) if you're upgrading from a previous version.\n\n## Dependencies\n\n* \u0026gt;= Ruby v2.2\n* \u0026gt;= [grape](https://github.com/ruby-grape/grape) v0.8.0\n* \u0026gt;= [active_model_serializers](https://github.com/rails-api/active_model_serializers) v0.10.0\n\n## Usage\n\n### Require grape-active_model_serializers\n\n```ruby\n# config.ru\nrequire 'grape-active_model_serializers'\n```\n\n### Tell your API to use Grape::Formatter::ActiveModelSerializers\n\n```ruby\nclass API \u003c Grape::API\n  format :json\n  formatter :json, Grape::Formatter::ActiveModelSerializers\n\n  # Serializes errors with ActiveModel::Serializer::ErrorSerializer if an ActiveModel.\n  # Serializer conforms to the adapter, ex: json, jsonapi.\n  # So an error formatted with a jsonapi formatter would render as per:\n  # http://jsonapi.org/format/#error-objects\n  error_formatter :json, Grape::Formatter::ActiveModelSerializers\nend\n```\n\n### Writing Serializers\n\nSee [active_model_serializers](https://github.com/rails-api/active_model_serializers)\n\n\n### Serializers are inferred by active_record model names\n\n`grape-active_model_serializers` will search for serializers for the objects returned by your grape API.\n\n```ruby\nnamespace :users do\n  get \":id\" do\n    @user = User.find(params[:id])\n  end\nend\n```\nIn this case, as User objects are being returned, grape-active_model_serializers will look for a serializer named UserSerializer.\n\n### Array Roots\n\nWhen serializing an array, the array root is set to the innermost namespace name if there is one, otherwise it is set to the route name.\n\nIn the following API the array root is `users`.\n\n```ruby\nnamespace :users do\n  get \":id\" do\n    @user = User.find(params[:id])\n  end\nend\n```\n\nIn the following example the array root is `people`.\n\n```ruby\nget \"people\" do\n  @user = User.all\nend\n```\n\n### API Versioning\n\nIf your Grape API is versioned you must namespace your serializers accordingly.\n\nFor example, given the following API.\n\n```ruby\nmodule CandyBar\n  class Core \u003c Grape::API\n    version 'candy_bar', using: :header, vendor: 'acme'\n  end\nend\n\nmodule Chocolate\n  class Core \u003c Grape::API\n    version 'chocolate', using: :header, vendor: 'acme'\n  end\nend\n\nclass API \u003c Grape::API\n  format :json\n  formatter :json, Grape::Formatter::ActiveModelSerializers\n\n  mount CandyBar::Core\n  mount Chocolate::Core\nend\n```\n\nNamespace your serializers according to each version.\n\n```ruby\nmodule CandyBar\n  class UserSerializer \u003c ActiveModel::Serializer\n    attributes :first_name, :last_name, :email\n  end\nend\n\nmodule Chocolate\n  class UserSerializer \u003c ActiveModel::Serializer\n    attributes :first_name, :last_name\n  end\nend\n```\n\nThis keeps serializers organized.\n\n```\napp\n└── api\n    ├── chocolate\n        └── core.rb\n    └── candy_bar\n        └── core.rb\n    api.rb\n└── serializers\n    ├── chocolate\n        └── user_serializer.rb\n    └── candy_bar\n        └── user_serializer.rb\n```\n\nOr as follows.\n\n```\n└── serializers\n    ├── chocolate_user_serializer.rb\n    └── candy_bar_user_serializer.rb\n```\n\nActiveModelSerializer will fetch automatically the right serializer to render.\n\n### Manually specifying serializer / adapter options\n\n```ruby\n# Serializer and adapter options can be specified on routes or namespaces.\nnamespace 'foo', serializer: BarSerializer do\n  get \"/\" do\n    # will use \"bar\" serializer\n  end\n\n  # Options specified on a route or namespace override those of the containing namespace.\n  get \"/home\", serializer: HomeSerializer do\n    # will use \"home\" serializer\n  end\n\n  # All standard options for `ActiveModel::Serializers` are supported.\n  get \"/fancy_homes\", root: 'world', each_serializer: FancyHomesSerializer\n  ...\n  end\nend\n```\n\n```ruby\n# Serializer and adapter options can also be specified in the body of the route\nresource :users do\n  get '/:id' do\n    if conditional\n      # uses UserSerializer and configured default adapter automatically\n      current_user\n    else\n      # uses specified serializer and adapter\n      render current_user, serializer: ErrorSerializer, adapter: :attributes\n    end\n  end\nend\n```\n\n```ruby\n# Adhoc serializer options can be specified in the body of the route\nresource :users do\n  get '/:id' do\n    render current_user, extra: { adhoc_name_option: 'value' }\n  end\nend\n\nclass UserSerializer\n  def name\n    instance_options[:adhoc_name_option] # accessible in instance_options\n  end\nend\n```\n\n### Custom Metadata\n\n```ruby\n# Control any additional metadata using meta and meta_key\nget \"/homes\"\n  collection = Home.all\n  render collection, { meta: { page: 5, current_page: 3 }, meta_key: :pagination_info }\nend\n```\n\n### Default Serializer Options\n\n```ruby\nhelpers do\n  def default_serializer_options\n    { only: params[:only], except: params[:except] }\n  end\nend\n```\n\n### Current User\n\nOne of the nice features of ActiveModel::Serializers is that it provides access to the authorization context via the `current_user`.\n\nIn Grape, you can get the same behavior by defining a `current_user` helper method.\n\n```ruby\nhelpers do\n  def current_user\n    @current_user ||= User.where(access_token: params[:token]).first\n  end\n\n  def authenticate!\n    error!('401 Unauthenticated', 401) unless current_user\n  end\nend\n```\n\nThen, in your serializer, you could show or hide some elements based on the current user's permissions.\n\n```ruby\nclass PostSerializer \u003c ActiveModel::Serializer\n  def include_admin_comments?\n    current_user.roles.member? :admin\n  end\nend\n```\n\n*Note*: in the [0.9.x stable version of active model serializers](https://github.com/rails-api/active_model_serializers/tree/0-9-stable#customizing-scope), you have to access current user on scope -  so `scope.current_user`.\n\n### Full Example\n\n```ruby\nclass User \u003c ActiveRecord::Base\n  attr_accessor :first_name, :last_name, :password, :email\nend\n\nclass UserSerializer \u003c ActiveModel::Serializer\n  attributes :first_name, :last_name\nend\n\nclass API \u003c Grape::API\n  get(\"/home\") do\n    User.new({first_name: 'JR', last_name: 'HE', email: 'contact@jrhe.co.uk'})\n  end\nend\n\nAPI.new.get \"/home\" # =\u003e '{ user: { first_name: \"JR\", last_name: \"HE\" } }'\n```\n\n## Contributing\n\nSee [CONTRIBUTING](CONTRIBUTING.md).\n\n## History\n\nStructured and based upon [grape-rabl](https://github.com/ruby-grape/grape-rabl).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fruby-grape%2Fgrape-active_model_serializers","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fruby-grape%2Fgrape-active_model_serializers","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fruby-grape%2Fgrape-active_model_serializers/lists"}