Considere esta solución. Biblioteca + especificaciones:
del archivo: lib/ext/hash/from_string.rb
:
require "json"
module Ext
module Hash
module ClassMethods
# Build a new object from string representation.
#
# from_string('{"name"=>"Joe"}')
def from_string(s)
s.gsub!(/(?<!\\)"=>nil/, '":null')
s.gsub!(/(?<!\\)"=>/, '":')
JSON.parse(s)
end
end
end
end
class Hash #:nodoc:
extend Ext::Hash::ClassMethods
end
del archivo: spec/lib/ext/hash/from_string_spec.rb
:
require "ext/hash/from_string"
require "rspec/match_result" # Get from https://github.com/dadooda/rspec_match_result.
describe "Hash.from_string" do
it "generally works" do
[
# Basic cases.
['{"x"=>"y"}', {"x" => "y"}],
['{"is"=>true}', {"is" => true}],
['{"is"=>false}', {"is" => false}],
['{"is"=>nil}', {"is" => nil}],
['{"a"=>{"b"=>"c","ar":[1,2]}}', {"a" => {"b" => "c", "ar" => [1, 2]}}],
['{"id"=>34030, "users"=>[14105]}', {"id" => 34030, "users" => [14105]}],
# Tricky cases.
['{"data"=>"{\"x\"=>\"y\"}"}', {"data" => "{\"x\"=>\"y\"}"}], # Value is a `Hash#inspect` string which must be preserved.
].each do |input, expected|
match_result(input, expected) {|input| Hash.from_string(input)}
end
end # it
end
Creo que eval hará algo aquí. Déjame probar primero. Publiqué la pregunta demasiado pronto, creo. :) – Waseem
Ohh, sí, simplemente pásalo a la evaluación. :) – Waseem