YAML

YAML stands for Yet Another Markup Language and later YAML Ain’t Markup Language

YAML is a data serialization format that is easy to read as well as designed to be easily mapped to data types of various programming languages. Here is an example of a basic YAML file:

customer:
    name: 'Ashutosh Pandey'
    city: 'New Delhi'
    order:
      item1: 
         name: 'Nexus 6'
         quantiy: 1
         price: 40000

Reading YAML

YAML is added in rails by default. So, let us create an example for reading YAML data in our rails application.

Here are the steps:

  1. Create a new rails project or use an existing one.
  2. Let us create a new file named test.yml inside the config folder and put following data in it:
    Development:
      database:
        username: 'dev_user'
        password: 'dev_password'
        dbname: 'db_dev'
    
    Testing:
      database:
        username: 'test_user'
        password: 'test_password'
        dbname: 'db_test'
  3. Now, we will create a controller with a single action. This action will read our test.yml file and prints out the data.
    rails generate controller test ymldata
  4. Add following logic to the class:
    require 'yaml'
    
    class TestController < ApplicationController
       def ymldata
         config = YAML.load_file("config/test.yml")
    
         development_dbname = config['Development']['database']['dbname']
         development_username = config['Development']['database']['dbname']
         development_password = config['Development']['database']['password']
    
         result = "<b>Development database settings</b><br/>"
         result += "Database name = " + development_dbname + "<br/>"
         result += "Username = " + development_username + "<br/>"
         result += "Password = " + development_password + "<br/>"
    
         render :html => result.html_safe
       end
    end
  5. Add following line to your config\routes.rb file:
    get 'test/ymldata'
  6. Now start the rails server and visit the URL:
    http://localhost:3000/test/ymldata

Writing YAML

Writing data to YAML is also easy. Here is an example:

  1. First we will create a model named Student so that we can create and write student objects to YAML file.
    Create a new file named student.rb in app\models folder. Add following code to the file:

    class Student
    
      def initialize(id, name, gender)
        @id = id
        @name = name
        @gender = gender
      end
    end
  2. Now, create following action in the test controller:
    def toyaml
    
      s1 = Student.new(1, 'Ashutosh Pandey', 'Male')
      s2 = Student.new(2, 'Ruchira Mishra', 'Female')
      s3 = Student.new(3, 'Shiva Pandey', 'Male')
    
      File.open("tmp/students.yaml", "w") do |file|
          file.puts YAML::dump(s1)
          file.puts YAML::dump(s2)
          file.puts YAML::dump(s3)
          file.puts ""
      end
    
      render :plain => "File created"
    end
  3. Add following line to the config\routes.rb file:
    get 'test/toyaml'
  4. Start your server and navigate to the URL:
    http://localhost:3000/test/toyaml

    You should see the students.yaml file created in the tmp folder of your project.

JSON

JSON stands for Javascript Object Notation

JSON is a lightweight data-interchange format. It is easy for humans as well as programming languages to read and write. Here is an example of a basic JSON file:

{
  "city"     :    "New Delhi",
  "country"  :    "India",
  "places"   :    {
    "1" : "Lal Qila",
    "2" : "National Museum"
  }
}

Let us create another example for reading JSON data in our rails application.

Here are the steps:

  1. Let us create a new file named test.json inside the config folder and put following data in it:
    {
      "city"     :    "New Delhi",
      "country"  :    "India",
      "places"   :    {
        "1" : "Lal Qila",
        "2" : "National Museum"
      }
    }
  2. Now, we will add a new action named readjson in our test controller. This action will read our test.json file and prints out the data.
  3. Add following logic to the class:
    require 'json'
    
    class TestController < ApplicationController
       # your existing actions here
    
       def readjson
          file = File.read('config/test.json')
    
          data = JSON.parse(file)
    
          city = data['city']
          country = data['country']
          place1 = data['places']['1']
          place2 = data['places']['2']
    
          str =  "Places to visit in " + city + "/" + country + "<br/>"
          str += "1. " + place1 + "<br/>"
          str += "2. " + place2 + "<br/>"
    
          render :html => str.html_safe
       end
    end
  4. Add following line to your config\routes.rb file:
    get 'test/readjson'
  5. Now start the rails server and visit the URL:
    http://localhost:3000/test/readjson

Writing JSON

Writing data to JSON is also easy. Here is an example:

  1. We already have a model named Student.
  2. Now, create a new action named tojson in the test controller and add the following code:
    def tojson
    
      s1 = Student.new(1, 'Ashutosh Pandey', 'Male')
      s2 = Student.new(2, 'Ruchira Mishra', 'Female')
      s3 = Student.new(3, 'Shiva Pandey', 'Male')
    
      students = []
    
      students.push(s1)
      students.push(s2)
      students.push(s3)
    
      File.open("tmp/students.json", "w") do |file|
        file.puts students.to_json
      end
    
      render :plain => "File created"
    end
  3. Add following line to the config\routes.rb file:
    get 'test/tojson'
  4. Start your server and navigate to the URL:
    http://localhost:3000/test/tojson

CSV

CSV stands for Comma Seperated Value

CSV is a type of text file in which fields are separated by comma. It is easy for humans as well as programming languages to read and write. Here is an example of a CSV data:

1,India,New Delhi
2,Australia,Melbourne
3,Russia,Moscow

Let us create another example for reading CSV file in our rails application.

Here are the steps:

  1. Let us create a new file named students.csv inside the config folder and put following data in it:
    1,Ashutosh Pandey,Male
    2,Ruchira Mishra,Female
    3,Shiva Pandey,Male
  2. Now, we will add a new action named readcsv in our test controller. This action will read our students.csv file and prints out the data.
  3. Add following logic to the class:
    require 'csv'
    
    class TestController < ApplicationController
       # your existing actions here
    
       def readjson
          data = ""
          CSV.foreach('tmp/students.csv') do |row|
              data += row.to_s + "<br/>"       # row is an array here, converting to string
          end
    
          render :html => data.html_safe
       end 
    end
  4. Add following line to your config\routes.rb file:
    get 'test/readcsv'
  5. Now start the rails server and visit the URL:
    http://localhost:3000/test/readcsv

Writing CSV

Here is an example to write our data to CSV file:

  1. We already have a model named Student.
  2. Now, create a new action named tocsv in the test controller and add the following code:
    def tocsv
       ar = []
    
       ar.push([1, 'Ashutosh Pandey', 'Male'])
       ar.push([2, 'Ruchira Mishra', 'Female'])
       ar.push([3, 'Shiva Pandey', 'Male'])
    
       CSV.open "tmp/students.csv", "w"  do |file|
          ar.each do |data|
            file << data
          end
       end
    
       render :plain => "File created"
    end
  3. Add following line to the config\routes.rb file:
    get 'test/tocsv'
  4. Start your server and navigate to the URL:
    http://localhost:3000/test/tocsv