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?

有帮助吗?

解决方案

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top