Created
October 15, 2013 14:08
-
-
Save ivanbrennan/6992145 to your computer and use it in GitHub Desktop.
Serialize
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| RSpec.configure do |config| | |
| # Use color in STDOUT | |
| config.color_enabled = true | |
| # Use color not only in STDOUT but also in pagers and files | |
| config.tty = true | |
| # Use the specified formatter | |
| config.formatter = :progress # :progress, :html, :textmate | |
| end | |
| #implement a song class and artist class to pass the specs below. | |
| #serialize method should replace spaces in the song title with underscores | |
| #and write to the current working directory | |
| class Song | |
| attr_accessor :title, :artist | |
| def initialize(title=nil) | |
| @title = title | |
| end | |
| def serialize | |
| file_name = title.downcase.gsub(" ","_") << ".txt" | |
| file_text = "#{artist.name} - #{title}" | |
| File.open(file_name,"w") { |file| file.write(file_text) } | |
| end | |
| def self.deserialize(file_name) | |
| File.open(file_name,"r") do |text| | |
| line = IO.readlines(text).first | |
| artist_name, song_title = line.split(" - ") | |
| Song.new(song_title).tap do |song| | |
| song.artist = Artist.new(artist_name) | |
| end | |
| end | |
| end | |
| end | |
| class Artist | |
| attr_reader :name | |
| def initialize(name) | |
| @name = name | |
| end | |
| end | |
| describe Song do | |
| it "has a title" do | |
| song = Song.new | |
| song.title = "Night Moves" | |
| song.title.should eq("Night Moves") | |
| end | |
| it "has an artist" do | |
| song = Song.new | |
| song.title = "Night Moves" | |
| song.artist = Artist.new("Bob Seger") | |
| song.artist.name.should eq("Bob Seger") | |
| end | |
| it "can save a representation of itself to a file" do | |
| song = Song.new | |
| song.title = "Night Moves" | |
| song.artist = Artist.new("Bob Seger") | |
| song.serialize | |
| File.read("night_moves.txt").should match /Bob Seger - Night Moves/ | |
| end | |
| it "can instantiate a song from a serialized file" do | |
| file = File.open("spottie_ottie.txt","w") { |f| f.write("Outkast - Spottie Ottie")} | |
| song = Song.deserialize("spottie_ottie.txt") | |
| end | |
| it "instantiates song with correct attributes from serialized file" do | |
| file = File.open("spottie_ottie.txt","w") { |f| f.write("Outkast - Spottie Ottie")} | |
| song = Song.deserialize("spottie_ottie.txt") | |
| song.title.should eq("Spottie Ottie") | |
| song.artist.name.should eq("Outkast") | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment