A YAML Database

For an example of a slightly more complicated application that saves and loads data in YAML format, take a look at the cd_db.rb sample program. This implements a simple CD database. It defines three types of CD objects: a basic CD that contains data on the name, artist, and number of tracks; and two more specialized descendants, PopCD, which adds data on the genre (for example, rock or country), and ClassicalCD, which adds data on the conductor and composer:

cd_db.rb

class CD
    def initialize( arr )
        @name       = arr[0]
        @artist     = arr[1]
        @numtracks  = arr[2]
    end

    def getdetails
        return[@name, @artist, @numtracks]
    end
end

class PopCD < CD

    def initialize( arr )
        super( arr  )
        @genre = arr[3]
    end

    def getdetails
        return( super << @genre )
    end
end

class ClassicalCD < CD
    def initialize( arr )
        super( arr )
        @conductor  = arr[3]
        @composer   = arr[4]
    end

    def getdetails
        return( super << @conductor << @composer )
    end
end

When the program is run, the user can enter data to create new CD objects of any of these three types. There is also an option to save data to disk. When the application is run subsequently, the existing data is reloaded.

The data itself is organized very simply (trivially even) in the code, with the data for each object being read into an array before the object itself is created. The whole database of CD objects is saved into the global variable $cd_arr, and this is written to disk and reloaded into memory using YAML methods:

def saveDB
    File.open( $fn, 'w' ) {
        |f|
        f.write($cd_arr.to_yaml)
    }
end

def loadDB
    input_data = File.read( $fn )
    $cd_arr = YAML::load( input_data )
end

Bear in mind that this program has been written for simplicity rather than beauty. In a real-world application, you would, I am sure, want to create somewhat more elegant data structures to manage your Dolly Parton collection!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.201.217