grape-entity
grape-entity copied to clipboard
convert `mongoid bson object ` into string by default
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?
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