How to read data from a different file without using YAML or JSON

111 Views Asked by At

I'm experimenting with a Ruby script that will add data to a Neo4j database using REST API. (Here's the tutorial with all the code if interested.)

The script works if I include the hash data structure in the initialize method but I would like to move the data into a different file so I can make changes to it separately using a different script.

I'm relatively new to Ruby. If I copy the following data structure into a separate file, is there a simple way to read it from my existing script when I call @data? I've heard one could do something with YAML or JSON (not familiar with how either work). What's the easiest way to read a file and how could I go about coding that?

#I want to copy this data into a different file and read it with my script when I call @data.
{
  nodes:[
        {:label=>"Person", :title=>"title_here", :name=>"name_here"}
        ]
} 

And here is part of my code, it should be enough for the purposes of this question.

class RGraph

  def initialize    

    @url = 'http://localhost:7474/db/data/cypher'

    #If I put this hash structure into a different file, how do I make @data read that file?
    @data = {
            nodes:[
                {:label=>"Person", :title=>"title_here", :name=>"name_here"}
            ]
            } 


  end

  #more code here... not relevant to question

  def create_nodes
    # Scan file, find each node and create it in Neo4j
    @data.each do |key,value|
        if key == :nodes
            @data[key].each do |node| # Cycle through each node
                next unless node.has_key?(:label) # Make sure this node has a label
                #WE have sufficient data to create a node
                label = node[:label]
                attr = Hash.new
                node.each do |k,v| # Hunt for additional attributes
                    next if k == :label # Don't create an attribute for "label"
                    attr[k] = v
                end
                create_node(label,attr)
             end
          end
      end
  end

rGraph = RGraph.new

rGraph.create_nodes

end
1

There are 1 best solutions below

1
Amadan On BEST ANSWER

Given that OP said in comments "I'm not against using either of those", let's do it in YAML (which preserves the Ruby object structure best). Save it:

@data = {
        nodes:[
            {:label=>"Person", :title=>"title_here", :name=>"name_here"}
        ]
    } 
require 'yaml'
File.write('config.yaml', YAML.dump(@data))

This will create config.yaml:

---
:nodes:
- :label: Person
  :title: title_here
  :name: name_here

If you read it in, you get exactly what you saved:

require 'yaml'
@data = YAML.load(File.read('config.yaml'))
puts @data.inspect
# => {:nodes=>[{:label=>"Person", :title=>"title_here", :name=>"name_here"}]}