How to filter properties/collections out from representers?

1.1k views Asked by At

For example, I have a representer looking like:

module AccountRepresenter

  include Roar::Representer::JSON
  include Roar::Representer::Feature::Hypermedia

  property :id
  property :name

  collection :assets, :extend => AssetRepresenter, :class => Asset
end

In controller I use it as:

respond_with @accounts, represent_with: AccountsRepresenter

For another action I don't want collection :assets to be presented. I tried

respond_with @accounts, represent_with: AccountsRepresenter, exclude: :assets

But it doesn't work. How should I pass argument into representers?

1

There are 1 answers

0
omarvelous On BEST ANSWER

The Roar gem uses Representable underneath (https://github.com/apotonick/representable#conditions). You can do the following things to have conditional functionality:

respond_with @accounts, represent_with: AccountsRepresenter, exclude: [:assets]

Then

module AccountRepresenter

  include Roar::Representer::JSON
  include Roar::Representer::Feature::Hypermedia

  property :id
  property :name

  collection :assets, extend: AssetRepresenter, if: lambda { |opts| !opts[:exclude].includes?(:assets)] }
end