葡萄实体中的宿主和港口

时间:2013-10-14 09:12:49

标签: ruby rack grape

我试图在生成网址时获取葡萄实体中的主机和端口

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

我曾尝试检查选项哈希,但'env'哈希是空的。

2 个答案:

答案 0 :(得分:2)

以下为我的作品,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

快速测试:

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

答案 1 :(得分:0)

最后,最终将主机作为选项发送给实体

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