rewrote write to use known attributes or instance variables, simple values inline

This commit is contained in:
Torsten Ruger 2014-08-14 19:49:20 +03:00
parent 7eeb269d50
commit 6b19b915a1
3 changed files with 40 additions and 16 deletions

View File

@ -1,4 +1,6 @@
require_relative "util"
require_relative "members"
require_relative "known"
require_relative "writer"
require_relative "array"
require_relative "occurence"
@ -25,7 +27,9 @@ FalseClass.class_eval do
end
String.class_eval do
def to_sof(io, members)
io.write "'"
io.write self
io.write "'"
end
end
Fixnum.class_eval do

View File

@ -1,5 +1,6 @@
module Sof
class Writer
include Util
def initialize members
@members = members
end
@ -11,7 +12,7 @@ module Sof
end
def output io , object
if Members.is_value?(object)
if is_value?(object)
object.to_sof(io , self)
return
end
@ -19,21 +20,33 @@ module Sof
raise "no object #{object}" unless occurence
indent = " " * occurence.level
io.write indent
if(object.respond_to? :to_sof)
if(object.respond_to? :to_sof) #mainly meant for arrays and hashes
object.to_sof(io , self)
else
io.write object.class.name
if( object.respond_to?(:attributes))
object.attributes.each do |a|
val = object.send a
io.write( a )
io.write( " " )
output( io , val)
end
io.puts ""
else
raise "General object not supported (yet), need attribute method #{object}"
end
object_write(object , io)
end
end
def object_write( object , io)
io.write object.class.name
io.write "("
attributes = attributes_for(object)
attributes.each_with_index do |a , i|
val = get_value(object , a)
next unless is_value?(val)
io.write( a )
io.write( ": " )
output( io , val)
io.write(" ,") unless i == (attributes.length - 1)
end
io.puts ")"
attributes.each_with_index do |a , i|
val = get_value(object , a)
next if is_value?(val)
io.puts " -"
io.write( a )
io.write( ": " )
output( io , val)
end
end

View File

@ -1,6 +1,10 @@
require_relative "helper"
class SimpleObjectWithAttributes
class ObjectWithAttributes
def initialize
@name = "some object"
@number = 1234
end
end
class BasicSof < MiniTest::Test
@ -13,5 +17,8 @@ class BasicSof < MiniTest::Test
out = Sof::Writer.write(124)
assert_equal "124" , out
end
def test_object
out = Sof::Writer.write(ObjectWithAttributes.new)
assert_equal " ObjectWithAttributes(name: 'some object' ,number: 1234)\n" , out
end
end