Sha256: 2012b2cb961ee9c130ab7649f4c8a15eb85ec67fe67f3f901f2c00137e7d830d
Contents?: true
Size: 1.75 KB
Versions: 12
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_rails do # 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
12 entries across 12 versions & 1 rubygems