# What is this code add\_to\_serializer in all these plugins

**URL:** <https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913>\
**Category:** Development\
**Created:** [March 12, 2017, 5:07am UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913 "2017-03-12T05:07:15Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![gdpelican](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/gdpelican/32/81308_2.png) [@gdpelican](https://meta.discourse.org/u/gdpelican)\
**Post date:** [March 12, 2017, 5:50am UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/2 "2017-03-12T05:50:30Z")

</div>

It’s essentially adding to the information that Discourse serializes out when sending that model to the client. For example, you may see a request to this endpoint when loading up a topic page:

```plaintext
http://meta.discourse.org/t/2349082394.json

```

which returns some payload like this:

```json
{
  title: "Some topic title",
  archetype: 'regular',
  category_id: 7,
  post_stream: { posts: [...] },
  posts_count: 15,
  (etc etc.. lots more info about the topic in question)
}

```

Which is the json representation of a Discourse topic.

If I want to know more about the topic because of additional ‘stuff’ I do in my plugin, I can put in a line like

```rb
add_to_serializer :topic, :flag_name do
  object.flag_name # <- NB that 'object' here is the topic being serialized
end

```

(Also, by default, this method simply sends the specified message to ‘object’, meaning that

```rb
add_to_serializer :topic, :flag_name

```

is the same as

```rb
add_to_serializer :topic, :flag_name do
  object.flag_name
end

```

)

Once I’ve added the method to the serializer, I can end up with JSON output which includes that additional info

```json
{
  title: "Some topic title",
  archetype: 'regular',
  category_id: 7,
  post_stream: { posts: [...] },
  posts_count: 15,
  flag_name: "some flag name"
  ...
}

```

Also note that you could achieve the same thing by overwriting the TopicSerializer class (which is exactly what the code snippet you’ve provided is doing)

```rb
# plugin.rb
TopicSerializer.class_eval do
  attributes :flag_name
  def flag_name
    object.flag_name
  end
end

```

---

_[View the full topic](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913)._
