最灵活地处理字符串数组

时间:2018-08-06 18:54:38

标签: ruby-on-rails ruby rest

我正在使用Flexirest向端点发出请求,该端点返回带有Content-Type: application\json的字符串数组。

这是模型:

class Neighborhood < BaseModel
  get :by_location, "/neighborhoods/by_location"
end 

这就是我发出请求的方式:

def get_neighborhood_list
  city_to_use = ApplicationHelper.user_location[:city] || Rails.configuration.default_location[:city]
  @hoods = Neighborhood.by_location(city: city_to_use)
end

这被称为,但仅到达super行,因为它在其中中断:

def handle_response(response, cached = nil)
  result = super(response, cached)
  setup_paging_variables result, response
  setup_paging_variables result.data, response if result.respond_to? 'data'
  result
end

端点返回一个字符串数组:

[
    "Ahwatukee Foothills Village",
    "Alhambra",
    "Camelback East Village",
    "Central City",
]

带有此标题

enter image description here

我的问题是,由于Content-Type标头上的值,Flexirest将字符串视为json对象,而不是。 我收到此错误

  

TypeError:没有将Symbol隐式转换为Integer

if attributes[:_links]的这一行上。 之所以到达那里是因为hal_response?是真的

为了让Flexirest停止这种行为,我需要做些特别的事情吗?


更新

我想我没有正确解释。错误发生在宝石侧。 这是完整的错误:

TypeError - no implicit conversion of Symbol into Integer:
  flexirest (1.5.5) lib/flexirest/request.rb:612:in `handle_hal_links_embedded'
  flexirest (1.5.5) lib/flexirest/request.rb:553:in `new_object'
  flexirest (1.5.5) lib/flexirest/request.rb:704:in `block in generate_new_object'
  flexirest (1.5.5) lib/flexirest/request.rb:703:in `generate_new_object'
  flexirest (1.5.5) lib/flexirest/request.rb:501:in `handle_response'
  config/initializers/01_flexirest.rb:7:in `handle_response'
  flexirest (1.5.5) lib/flexirest/request.rb:219:in `block (2 levels) in call'
  faraday (0.9.2) lib/faraday/response.rb:57:in `on_complete'
  flexirest (1.5.5) lib/flexirest/request.rb:200:in `block in call'
  activesupport (4.2.4) lib/active_support/notifications.rb:164:in `block in instrument'
  activesupport (4.2.4) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  activesupport (4.2.4) lib/active_support/notifications.rb:164:in `instrument'
  flexirest (1.5.5) lib/flexirest/request.rb:156:in `call'
  flexirest (1.5.5) lib/flexirest/mapping.rb:46:in `_call'
  flexirest (1.5.5) lib/flexirest/mapping.rb:28:in `block in _map_call'
  app/controllers/application_controller.rb:93:in `get_neighborhood_list

if attributes[:_links]行是gem代码的一部分,它是here on this line

到达此行时,attributes的值是响应内的字符串之一,例如:attributes = "Ahwatukee Foothills Village"。这就是为什么它会给出错误。

我要弄清楚的是,是否有一种方法(也许是配置中的某种方法)可以使用Flexirest处理此类响应。

1 个答案:

答案 0 :(得分:0)

这是一个古老的问题,但以为我会回答。您需要添加

  

纯文字:是

在您的模型中如下所示。

class Neighborhood < BaseModel
  get :by_location, "/neighborhoods/by_location", plain: true
end 

然后它将返回字符串数组