Question

Im trying to get the host and port in a grape-entity when generating an url

class Person < Grape::Entity
    expose :url do |person,options| 
        "http://#{host_somehow}/somepath/#{person.id}"
    end
end 

I´ve tried examining the options hash but the 'env' hash is empty.

Was it helpful?

Solution

Following works for me, Grape 0.6.0, Grape-Entity 0.3.0, Ruby 2.0.0:

require 'grape'
require 'grape-entity'

# in reality this would be Active Record, Data Mapper, whatever
module Model
  class Person
    attr_accessor :identity, :name
    def initialize i, n
      @identity = i
      @name = n
    end
  end
end

module APIView
  class Person < Grape::Entity
    expose :name
    expose(:url) do |person,opts| 
      "http://#{opts[:env]['HTTP_HOST']}" + 
        "/api/v1/people/id/#{person.identity}"
    end
  end
end

class MyApp < Grape::API
  prefix      'api'
  version     'v1'
  format      :json

  resource :people do
    get "id/:identity" do
      person = Model::Person.new( params['identity'], "Fred" )
      present person, :with => APIView::Person
    end
  end
end

Quick test:

curl http://127.0.0.1:8090/api/v1/people/id/90

=> {"name":"Fred","url":"http://127.0.0.1:8090/api/v1/people/id/90"}

OTHER TIPS

Finally ended up with sending the host as a option to the entity

class Person < Grape::Entity
    expose :url do |person,options| 
        "http://#{options[:host]}/somepath/#{person.id}"
    end
end 

get '/' do
    @persons = Person.all
    present @persons, with: Person, host: request.host_with_port
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top