3

I'm using the awesome neography gem and have run into a slight problem converting the results of a Cypher query to a structured object (OpenStruct.new... )

I don't know how to create a hash or a OpenStruct from the columns and data query results, which are

{"columns"=>["p.pd_challenge_id", "p.author_id"], "data"=>[["158", "88"], ["158", "90"], ["158", "99"], ["158", "95"], ["158", "97"]]}

I cannot create a usable hash from it. .I've tried several things including

["data"].map{|x|{ "challenge_id" => x[1],"author_id"=>x[0]}}.to_json

results in

{{"challenge_id":158, "author_id":88}, {"challenge_id":158, "author_id":90}, {"challenge_id":158, "author_id":99}}    etc..   (to which I simply cannot convert to a hash or openstruct)

What I'm looking for is for something like the following stored in a struct object so the scaffolded view can read it unmodified:

{:challenge_id=>158, :author_id=>88}
{:challenge_id=>158, :author_id=>90}
{:challenge_id=>158, :author_id=>99}

my view would look for object.challenge_id

Now, I've tried to use to_sym on "challenge_id" to no avail while using .map method..

I've tried to Hash[@mydata] on ["data"] which also does not work

Is there a simple way to get all of this data into a structured object (OpenStruct.new .. ) so that my forms can simply read it as if it were reading the results of an active record query? I can do this with neo.get_node_properties but just can't seem to get this working right.

1 Answers1

6

Let's say you have two nodes, with a name and title.

cypher = "start n = node(1,2) return n.name as name, n.title as title"
results = @neo.execute_query(cypher)
{"columns"=>["name", "title"], "data"=>[["Marc", "awesome"], ["Tom", "chief"]]} 

Then you take your results and do this:

array_of_hashes = results["data"].map {|row| Hash[*results["columns"].zip(row).flatten] }

Which will leave you with :

[{"name"=>"Marc", "title"=>"awesome"}, {"name"=>"Tom", "title"=>"chief"}]

You can stop here or...

objects = array_of_hashes.map{|m| OpenStruct.new(m)}

[#<OpenStruct name="Marc", title="awesome">, #<OpenStruct name="Tom", title="chief">]

Which you can then access

objects.first.name => "Marc"

Max De Marzi
  • 1,098
  • 6
  • 11
  • 1
    Max - this is a great answer, but what about null values? When the data contains them, the resulting struct is not out of alignment - data is in the wrong columns.. Any way to preserve null values? – Ruben Catchme Obregon May 08 '13 at 23:45