ruby-on-railsrails-roar

How to filter properties/collections out from representers?


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?


Solution

  • 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