Search code examples
rubyrackruby-grape

host and port in a grape entity


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.


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"}