Class: Grape::Entity

Inherits:
Object
  • Object
show all
Defined in:
lib/grape/entity.rb

Overview

An Entity is a lightweight structure that allows you to easily represent data from your application in a consistent and abstracted way in your API. Entities can also provide documentation for the fields exposed.

Entities are not independent structures, rather, they create representations of other Ruby objects using a number of methods that are convenient for use in an API. Once you’ve defined an Entity, you can use it in your API like this:

Examples:

Entity Definition


module API
  module Entities
    class User < Grape::Entity
      expose :first_name, :last_name, :screen_name, :location
      expose :field, :documentation => {:type => "string", :desc => "describe the field"}
      expose :latest_status, :using => API::Status, :as => :status, :unless => {:collection => true}
      expose :email, :if => {:type => :full}
      expose :new_attribute, :if => {:version => 'v2'}
      expose(:name){|model,options| [model.first_name, model.last_name].join(' ')}
    end
  end
end

Usage in the API Layer


module API
  class Users < Grape::API
    version 'v2'

    desc 'User index', { :object_fields => API::Entities::User.documentation }
    get '/users' do
      @users = User.all
      type = current_user.admin? ? :full : :default
      present @users, :with => API::Entities::User, :type => type
    end
  end
end

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, options = {}) ⇒ Entity

Returns a new instance of Entity.



235
236
237
# File 'lib/grape/entity.rb', line 235

def initialize(object, options = {})
  @object, @options = object, options
end

Instance Attribute Details

#objectObject (readonly)

Returns the value of attribute object.



44
45
46
# File 'lib/grape/entity.rb', line 44

def object
  @object
end

#optionsObject (readonly)

Returns the value of attribute options.



44
45
46
# File 'lib/grape/entity.rb', line 44

def options
  @options
end

Class Method Details

.documentationObject

Returns a hash, the keys are symbolized references to fields in the entity, the values are document keys in the entity’s documentation key. When calling #docmentation, any exposure without a documentation key will be ignored.



104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/grape/entity.rb', line 104

def self.documentation
  @documentation ||= exposures.inject({}) do |memo, value|
                       unless value[1][:documentation].nil? || value[1][:documentation].empty?
                         memo[value[0]] = value[1][:documentation] 
                       end
                       memo
                     end

  if superclass.respond_to? :documentation
    @documentation = superclass.documentation.merge(@documentation)
  end

  @documentation
end

.expose(*args, &block) ⇒ Object

This method is the primary means by which you will declare what attributes should be exposed by the entity.

Parameters:

  • options (Hash)

    a customizable set of options

Raises:

  • (ArgumentError)


71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/grape/entity.rb', line 71

def self.expose(*args, &block)
  options = args.last.is_a?(Hash) ? args.pop : {}

  if args.size > 1
    raise ArgumentError, "You may not use the :as option on multi-attribute exposures." if options[:as]
    raise ArgumentError, "You may not use block-setting on multi-attribute exposures." if block_given?
  end

  raise ArgumentError, "You may not use block-setting when also using format_with" if block_given? && options[:format_with].respond_to?(:call)

  options[:proc] = block if block_given?

  args.each do |attribute|
    exposures[attribute.to_sym] = options
  end
end

.exposuresObject

Returns a hash of exposures that have been declared for this Entity or ancestors. The keys are symbolized references to methods on the containing object, the values are the options that were passed into expose.



91
92
93
94
95
96
97
98
99
# File 'lib/grape/entity.rb', line 91

def self.exposures
  @exposures ||= {}

  if superclass.respond_to? :exposures
    @exposures = superclass.exposures.merge(@exposures)
  end

  @exposures
end

.format_with(name, &block) ⇒ Object

This allows you to declare a Proc in which exposures can be formatted with. It take a block with an arity of 1 which is passed as the value of the exposed attribute.

Examples:

Formatter declaration


module API
  module Entities
    class User < Grape::Entity
      format_with :timestamp do |date|
        date.strftime('%m/%d/%Y')
      end

      expose :birthday, :last_signed_in, :format_with => :timestamp
    end
  end
end

Formatters are available to all decendants


Grape::Entity.format_with :timestamp do |date|
  date.strftime('%m/%d/%Y')
end

Parameters:

  • name (Symbol)

    the name of the formatter

  • block (Proc)

    the block that will interpret the exposed attribute

Raises:

  • (ArgumentError)


147
148
149
150
# File 'lib/grape/entity.rb', line 147

def self.format_with(name, &block)
  raise ArgumentError, "You must pass a block for formatters" unless block_given?
  formatters[name.to_sym] = block
end

.formattersObject

Returns a hash of all formatters that are registered for this and it’s ancestors.



153
154
155
156
157
158
159
160
161
# File 'lib/grape/entity.rb', line 153

def self.formatters
  @formatters ||= {}

  if superclass.respond_to? :formatters
    @formatters = superclass.formatters.merge(@formatters)
  end

  @formatters
end

.represent(objects, options = {}) ⇒ Object

This convenience method allows you to instantiate one or more entities by passing either a singular or collection of objects. Each object will be initialized with the same options. If an array of objects is passed in, an array of entities will be returned. If a single object is passed in, a single entity will be returned.

  entity. Pass nil or false to represent the object or objects with no

root name even if one is defined for the entity.

Parameters:

  • objects (Object or Array)

    One or more objects to be represented.

  • options (Hash) (defaults to: {})

    Options that will be passed through to each entity representation.

Options Hash (options):

  • :root (String)

    override the default root name set for the



220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/grape/entity.rb', line 220

def self.represent(objects, options = {})
  inner = if objects.respond_to?(:to_ary)
    objects.to_ary().map{|o| self.new(o, {:collection => true}.merge(options))}
  else
    self.new(objects, options)
  end

  root_element = if options.has_key?(:root)
    options[:root]
  else
    objects.respond_to?(:to_ary) ? @collection_root : @root
  end
  root_element ? { root_element => inner } : inner
end

.root(plural, singular = nil) ⇒ Object

This allows you to set a root element name for your representation.

Examples:

Entity Definition


module API
  module Entities
    class User < Grape::Entity
      root 'users', 'user'
      expose :id
    end
  end
end

Usage in the API Layer


module API
  class Users < Grape::API
    version 'v2'

    # this will render { "users": [ {"id":"1"}, {"id":"2"} ] }
    get '/users' do
      @users = User.all
      present @users, :with => API::Entities::User
    end

    # this will render { "user": {"id":"1"} }
    get '/users/:id' do
      @user = User.find(params[:id])
      present @user, :with => API::Entities::User
    end
  end
end

Parameters:

  • plural (String)

    the root key to use when representing a collection of objects. If missing or nil, no root key will be used when representing collections of objects.

  • singular (String) (defaults to: nil)

    the root key to use when representing a single object. If missing or nil, no root key will be used when representing an individual object.



202
203
204
205
# File 'lib/grape/entity.rb', line 202

def self.root(plural, singular=nil)
  @collection_root = plural
  @root = singular
end

Instance Method Details

#documentationObject



243
244
245
# File 'lib/grape/entity.rb', line 243

def documentation
  self.class.documentation
end

#exposuresObject



239
240
241
# File 'lib/grape/entity.rb', line 239

def exposures
  self.class.exposures
end

#formattersObject



247
248
249
# File 'lib/grape/entity.rb', line 247

def formatters
  self.class.formatters
end

#serializable_hash(runtime_options = {}) ⇒ Object Also known as: as_json

The serializable hash is the Entity’s primary output. It is the transformed hash for the given data model and is used as the basis for serialization to JSON and other formats.

Parameters:

  • options (Hash)

    Any options you pass in here will be known to the entity representation, this is where you can trigger things from conditional options etc.



258
259
260
261
262
263
264
265
# File 'lib/grape/entity.rb', line 258

def serializable_hash(runtime_options = {})
  return nil if object.nil?
  opts = options.merge(runtime_options || {})
  exposures.inject({}) do |output, (attribute, exposure_options)|
    output[key_for(attribute)] = value_for(attribute, opts) if conditions_met?(exposure_options, opts)
    output
  end
end