2

What I'm trying to do is to reuse type and description across grape and grape-entity gems.

In the documentation I read the following:

You can use entity documentation directly in the params block with using: Entity.documentation.

module API
  class Statuses < Grape::API
    version 'v1'
    desc 'Create a status'
    params do
      requires :all, except: [:ip], using: API::Entities::Status.documentation.except(:id)
    end
    post '/status' do
      Status.create! params
    end
  end
end

This allows me to use field description and field type from the documentation defined in the Grape Entity.

Whenever I define an API that requires only 1 field though, I need to do something like this (which I find kind of dirty):

given:

module Entities
  class Host < Grape::Entity
    expose :id
    # ... exposing some other fields ...
    expose :mac_address, documentation: { type: String, desc: "The mac address of the host" }
    expose :created_at, documentation: { type: DateTime, desc: "Record creation date" }
    expose :updated _at, documentation: { type: DateTime, desc: "Record update date" }
  end
end

I can do:

params do
  requires :mac_address, type: V1::Entities::Host.documentation[:mac_address][:type], desc: V1::Entities::Host.documentation[:mac_address][:desc]
end

I don't like the above solution mainly for 2 reasons:

  • I don't like to use the field "type" of an helper that was meant to support documentation generation.
  • It is cumbersome.

Is there a better way to share type and description across the 2 gems?

Joe
  • 41,484
  • 20
  • 104
  • 125
Francesco Meli
  • 2,484
  • 2
  • 21
  • 52

1 Answers1

0

You can do like this

module API
  class Statuses < Grape::API
    version 'v1'
    desc 'Create a status' do
      params API::Entities::Status.documentation.except(:created_at, :updated _at)
    end
    post '/status' do
      Status.create! params
    end
  end
end

This will give you only mac_address as a params not all.

Mayur Shah
  • 3,344
  • 1
  • 22
  • 41