Skip to content

Instantly share code, notes, and snippets.

@davelyon
Created April 8, 2010 12:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davelyon/360042 to your computer and use it in GitHub Desktop.
Save davelyon/360042 to your computer and use it in GitHub Desktop.
# Base class for an Item
class LibraryItem
# Type is a depricated method, undefining it will be safe
undef_method :type
# Dynamically generates Getters/Setters for class
# get_set :name, ConstClass
def self.get_set(name, klass)
define_method(name) {
instance_variable_get("@#{name}").value
}
define_method("#{name}=") { |args|
instance_variable_set("@#{name}", klass.new(args))
}
define_method("visit_#{name}") {
instance_variable_get("@#{name}")
}
end
def self.new_item(string)
vals =[]
string.each(',') { |val| vals << val.chomp(',') }
vals.reverse!
return Book.new(vals) if string =~ /^Book/
return DVD.new(vals) if string =~ /^DVD/
return CD.new(vals) if string =~/^CD/
return Periodical.new(vals) if string =~ /^Periodical/
end
def initialize(vars)
if vars.instance_of?(Array)
new_from_array(vars)
end
if vars.instance_of?(Hash)
vars.each do |key,value|
self.send("#{key}=",value)
end
end
end
def accept(visitor)
visitor.pre_visit(self)
visitor.send("visit_#{self.class.to_s.downcase}", self)
visitor.post_visit(self)
end
# Returns a list of all keys for each class
def all_keys
self.instance_variables.select {|var| var.delete!("@")}
end
def new_from_array(ary)
dict = {}
self.type = ary.pop
self.schemaVersionNumber = ary.pop
self.uniqueId = ary.pop
self.title = ary.pop
end
get_set :type,Type
get_set :schemaVersionNumber, SchemaVersionNumber
get_set :uniqueId, UniqueId
get_set :title, Title
end
# Specific subclass Book has attrs Author and Publisher
class Book < LibraryItem
get_set :author, Author
get_set :publisher, Publisher
def new_from_array(ary)
dict = super
self.author = ary.pop
self.publisher = ary.pop
end
end
# Specific subclass CD has attrs Artist, Genre, Year
class CD < LibraryItem
get_set :artist, Artist
get_set :genre, Genre
get_set :year, Year
def new_from_array(ary)
dict = super
self.artist = ary.pop
self.genre = ary.pop
self.year = ary.pop
end
end
# Specific subclass DVD has attrs Genre, Year
class DVD < LibraryItem
get_set :genre, Genre
get_set :year, Year
def new_from_array(ary)
dict = super
self.genre = ary.pop
self.year = ary.pop
end
end
# Specific class Periodical has attrs Volume, Issue
class Periodical < LibraryItem
get_set :volume, Volume
get_set :issue, Issue
def new_from_array(ary)
dict = super
self.volume = ary.pop
self.issue = ary.pop
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment