0

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

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

我试过检查选项散列,但“env”散列是空的。

4

2 回答 2

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"}
于 2013-10-14T10:12:26.733 回答
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
于 2013-10-14T13:34:13.050 回答