Sha256: 4dc57cdb1304a9b34b22fd835cd3ba3eeabe0260f7669522832c057267112ab1

Contents?: true

Size: 1.75 KB

Versions: 3

Compression:

Stored size: 1.75 KB

Contents

# Decorator

Decorator is mostly used whit paginated results, because it can wrap ActiveRecord relations in a "pagination-friendly" way

## Passing extra options to decorator

Let's say you want to decorate `comment`, but you also need `user` in order to print some details. Here is decorator for such comment:

```ruby
class CommentDecorator < SimpleDelegator
  include GraphqlRails::Decorator

  def initialize(comment, current_user)
    @comment = comment
    @current_user = user
  end

  def author_name
    if @current_user.can_see_author_name?(@comment)
      @comment.author_name
    else
      'secret author'
    end
  end
end
```

In order to decorate object with exra arguments, simply pass them to `.decorate` method. Like this:

```ruby
CommentDecorator.decorate(comment, current_user)
```

The only requirement is that first object should be the object which you are decorating. Other arguments are treated as extra data and they are not modified

## Decorating controller responses

If you want to decorate your controller response you can use `GraphqlRails::Decorator` module. It can decorate simple objects and ActiveRecord::Relation objects. This is very handy when you need to decorated paginated actions:

```ruby
class User < ActiveRecord::Base
  # it's not GraphqlRails::Model !
end

class UserDecorator < SimpleDelegator
  include GraphqlRails::Model
  include GraphqlRails::Decorator

  graphql do |c|
    # some setup, attributes, etc...
  end

  def initialize(user); end
end

class UsersController < GraphqlRails::Controller
  action(:index).paginated.returns('[UserDecorator!]!')

  def index
    users = User.where(active: true)
    UserDecorator.decorate(users)
  end

  def create
    user = User.create(params)
    UserDecorator.decorate(user)
  end
end
```

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
graphql_rails-3.0.0 docs/components/decorator.md
graphql_rails-2.4.0 docs/components/decorator.md
graphql_rails-2.3.0 docs/components/decorator.md