Class: PrintR::Generator
Instance Attribute Summary collapse
-
#object ⇒ Object
readonly
Returns the value of attribute object.
Instance Method Summary collapse
- #_to_str(obj, indent) ⇒ Object
- #generate ⇒ Object
-
#initialize(object) ⇒ Generator
constructor
A new instance of Generator.
Constructor Details
#initialize(object) ⇒ Generator
Returns a new instance of Generator.
8 9 10 11 |
# File 'lib/print_r/generator.rb', line 8 def initialize(object) @object = object @recursive_objects = nil end |
Instance Attribute Details
#object ⇒ Object (readonly)
Returns the value of attribute object.
6 7 8 |
# File 'lib/print_r/generator.rb', line 6 def object @object end |
Instance Method Details
#_to_str(obj, indent) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
# File 'lib/print_r/generator.rb', line 22 def _to_str(obj, indent) tab1 = " " * indent tab2 = " " * (indent+1) str = nil object_type = obj.class.name obj_id = obj.respond_to?(:object_id) ? obj.object_id : obj.__id__ case obj when Array # hash of values with index obj2 = {} obj.each_with_index do |value,i| obj2[i] = value end obj = obj2 when Hash # do nothing when TrueClass # fixnum 1 obj = 1 when FalseClass # fixnum 0 # not compatible with print_r() of PHP obj = 0 when NilClass # empty string obj = "" when Exception # to hash obj = obj.instance_eval{ { :message => self., :backtrace => self.backtrace, } } else if obj.respond_to?(:instance_variables) && 0<obj.instance_variables.length # instance_variables obj = obj.instance_variables.inject({}) {|h,key| key_str = key.to_s.sub("@", "") h[key_str] = obj.instance_variable_get(key) h } elsif obj.respond_to?(:to_s) # to_s obj = obj.to_s end end # to string case obj when Hash str = "#{object_type} Object\n" is_recursive = 1<@recursive_objects[obj_id] @recursive_objects[obj_id] += 1 if is_recursive str += " *RECURSION*" else str += tab1 + "(\n" obj.each_pair do |key,value| str += sprintf("%s[%s] => %s\n", tab2, key, _to_str(value, indent+2)) end str += tab1 + ")\n" end @recursive_objects[obj_id] -= 1 else str = "#{obj}" end str end |
#generate ⇒ Object
13 14 15 16 17 18 19 20 |
# File 'lib/print_r/generator.rb', line 13 def generate begin @recursive_objects = Hash.new(0) _to_str(object, 0) ensure @recursive_objects = nil end end |