【问题标题】:host and port in a grape entity葡萄实体中的主机和端口
【发布时间】:2013-10-21 19:46:16
【问题描述】:

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

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

我已尝试检查选项哈希,但“env”哈希为空。

【问题讨论】:

    标签: ruby rack grape


    【解决方案1】:

    以下对我有用,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"}
    

    【讨论】:

    • 您好,感谢您的回复。我还需要对实例实体实例的引用。也许我的例子有点不清楚,我更新了它以更好地反映我的需要。
    • @Erik Johansson:好的,修改了这个例子。它仍然对我有用,不确定你哪里出错了。 . .
    • 好的,现在可以了,我只需要发送对 Person 的引用。谢谢
    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-27
      相关资源
      最近更新 更多