Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

Add DSL for attribute filter #574

wants to merge 1 commit into


None yet
6 participants

Now you can use if parameter to attributes like this:

class PostSerializer < ActiveModel::Serializer
  attributes :id, :title
  attributes :body, :author, :if => :shows_body_and_author?

  def shows_body_and_author?

lbeder commented Jun 20, 2014



mikegee commented Jun 22, 2014

Since the #filter method can accomplish this goal, I think you should make a stronger case for this feature. There will always be more "gold-plating" people will want on a given piece of software. Why should this make the cut?

I think the #filter method is non-intuitive. Perhaps this feature can replace it? That would be nice.

I think #filter is indeed non-intuitive but it should remain an option for backward compatibility reason.

My solution is a DSL over filter, very similar to Active Model validators or Rails filters (before_filter, after_filter, around_filter) syntax.

It feels natural to be able to filter attributes by having if clause when you define said attributes. Of course if you would like to accept the patch I would probably have to add full support for unless clause and option to use lambda instead of defining methods inside of the presenter itself.

class Doge < ActiveRecord::Serializer
  # Already implemented
  attributes :woof, :if => :woofs? 

  def woofs?
    object.respond_to? :woof

  # I will have to implement this
  attributes :wow, unless: -> (object) { object.persisted? } 

  def wow

Arjeno commented Jun 24, 2014

👍 Does this also work for associations?

rilian commented Jun 28, 2014

good idea 👍


steveklabnik commented Jul 28, 2014

I am not interested in significantly changing the DSL in 0.9, sorry! We'll consider this change for 0.10, though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment