grape-entity icon indicating copy to clipboard operation
grape-entity copied to clipboard

convert `mongoid bson object ` into string by default

Open hardywu opened this issue 11 years ago • 1 comments

I am writing codes like

      expose :store_id do |model|
        model.store_id.to_s
      end

everywhere.

Wouldn't it be great to have grape-entity to convert mongo bson object into string by default?

hardywu avatar Dec 21 '14 06:12 hardywu

You can do this creating a BaseEntity class which other entities extend, for example:

module API
  module Entities
    class BaseEntity < Grape::Entity
      expose :_id, documentation: { type: 'String', desc: 'BSON::ObjectId String' }, :format_with => :to_string
      format_with(:to_string) { |foo| foo.to_s }
    end
  end
end
require_relative 'base_entity'
module API
  module Entities
    class Book < BaseEntity
      # _id will be exposed through class inheritance
    end
  end
end

For models which override the default _id field name, like your example, you can still invoke :to_string.

require_relative 'base_entity'
module API
  module Entities
    class Store < BaseEntity
      expose :store_id, :format_with => :to_string
    end
  end
end

mphstudios avatar Feb 09 '15 03:02 mphstudios