An Exercise in Metaprogramming with Ruby

Tags:

An Exercise in Metaprogramming with Ruby

class DataRecord

def self.make(file_name)

# Open datafile and parse field names
data = File.new(file_name)
header = data.gets.chomp
data.close

# Get the classname, People, based on filename
class_name = File.basename(file_name,”.txt”).capitalize

# Define People class
# cf) To get a class already defined, call Object.get(“class_name”)
klass = Object.const_set(class_name,Class.new)
names = header.split(“,”)

# Following block will define instance methods for People.
klass.class_eval do
attr_accessor *names

# initialize
define_method(:initialize) do |*values|
names.each_with_index do |name,i|
instance_variable_set(“@”+name, values[i])
end
end

# to_s
define_method(:to_s) do
str = “<#{self.class}:" names.each {|name| str << " #{name}=#{self.send(name)}" } str + ">”
end

# inspect is the same as to_s
alias_method :inspect, :to_s
end

# Define class method, People.read.
def klass.read
array = []
data = File.new(self.to_s.downcase+”.txt”)
data.gets # throw away header
data.each do |line|
line.chomp!

# Getting data as an array
values = eval(“[#{line}]”)
array << self.new(*values) end data.close array end klass end end # Preparing data output = File.new("people.txt", "w") output << %{name,age,weight,height "Smith, John", 35, 175, "5'10" "Ford, Anne", 49, 142, "5'4" "Taylor, Burt", 55, 173, "5'10" "Zubrin, Candace", 23, 133, "5'6"} output.close # Look how DataRecord can be used DataRecord.make("people.txt") lines = People.read puts lines.to_s puts lines[0].name [/code]

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *