Ruby on Rails String to OpenStruct

安稳与你 提交于 2019-12-11 11:41:55

问题


I have the following OpenStruct object but if I call .class on it is a string. How do I turn it back into a OpenStruct object?

[
 #<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:


A little bit hacky, but I think achieves your goal:

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


来源:https://stackoverflow.com/questions/22765419/ruby-on-rails-string-to-openstruct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!