Ruby on Rails String to OpenStruct

时间:2014-03-31 15:16:05

标签: ruby-on-rails ruby openstruct

我有以下OpenStruct对象,但如果我调用.class就是一个字符串。如何将其重新转换为OpenStruct对象?

[
 #<OpenStruct source="hkepc.com", visits="8", visitBounceRate="37.5", avgTimeOnSite="199.375", pageviews="25", pageviewsPerVisit="3.125">, 
 #<OpenStruct source="1st-tag.co.uk", visits="6", visitBounceRate="100.0", avgTimeOnSite="0.0", pageviews="6", pageviewsPerVisit="1.0">, 
 #<OpenStruct source="facebook.com", visits="5", visitBounceRate="80.0", avgTimeOnSite="8.2", pageviews="6", pageviewsPerVisit="1.2">
]

1 个答案:

答案 0 :(得分:1)

有点hacky,但我认为实现了你的目标:

require 'ostruct'

string_array = '[
 #<OpenStruct source="hkepc.com", visits="8", visitBounceRate="37.5", avgTimeOnSite="199.375", pageviews="25", pageviewsPerVisit="3.125">, 
 #<OpenStruct source="1st-tag.co.uk", visits="6", visitBounceRate="100.0", avgTimeOnSite="0.0", pageviews="6", pageviewsPerVisit="1.0">, 
 #<OpenStruct source="facebook.com", visits="5", visitBounceRate="80.0", avgTimeOnSite="8.2", pageviews="6", pageviewsPerVisit="1.2">
]'

string_array.gsub(/(\n|#<OpenStruct|\[|\]|\s+)/, '').split('>,').map do |attrs|
  struct_attrs = attrs.split(',')
  attrs = struct_attrs.inject({}) do |hash, elem|
    hash[elem.split('=').first] = elem.split('=').last.gsub('"', '')
    hash
  end

  OpenStruct.new(attrs)
end