Module: TTM::Show
- Defined in:
- lib/tatum.rb
Overview
Builds the string representation of the given object. See TTM.show for details.
Class Method Summary collapse
-
.puts(obj, opts = {}) ⇒ Object
Determines the class of the given object and outputs a string representation of it using TTM.puts.
-
.show_array(myarr, opts) ⇒ Object
Outputs a string representation of each object in the array.
-
.show_hash(hsh, opts) ⇒ Object
Outputs a hash as a text table.
Class Method Details
.puts(obj, opts = {}) ⇒ Object
Determines the class of the given object and outputs a string representation of it using TTM.puts.
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 |
# File 'lib/tatum.rb', line 733 def self.puts(obj, opts={}) # nil if obj.nil? TTM.puts '[nil]' # hash elsif obj.is_a?(Hash) show_hash obj, opts # array elsif obj.is_a?(Array) show_array obj, opts # else just output else TTM.puts obj.to_s end # always return nil return nil end |
.show_array(myarr, opts) ⇒ Object
Outputs a string representation of each object in the array. Puts the output inside horizontal rules.
766 767 768 769 770 771 772 773 774 775 776 777 778 779 |
# File 'lib/tatum.rb', line 766 def self.show_array(myarr, opts) # if empty if myarr.empty? TTM.puts '[empty array]' # else there's stuff in the array else TTM.hr do myarr.each do |el| TTM.puts el end end end end |
.show_hash(hsh, opts) ⇒ Object
Outputs a hash as a text table.
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 |
# File 'lib/tatum.rb', line 791 def self.show_hash(hsh, opts) opts = {'sort'=>true}.merge(opts) # if empty, output string indicating so if hsh.empty? TTM.puts '[empty hash]' # else display hash as a table else require 'text-table' # table object table = Text::Table.new # get array of keys keys = hsh.keys # sort if necessary if opts['sort'] keys.sort!{|a,b| a.to_s.downcase <=> b.to_s.downcase} end # loop through keys keys.each do |k| # get value val = hsh[k] # if val is a hash, show a list of hash keys if val.is_a?(Hash) val = val.keys.sort{|a,b| a.to_s <=> b.to_s} val = val.map{|vk| vk.to_s} val = '{' + val.join(', ') + '}' # if array, join elements elsif val.is_a?(Array) val = val.map{|vk| vk.to_s} val = '[' + val.join(' | ') + ']' # trim value display else # val = val.to_s val = TTM.object_display_string(val) if val.length > 120 val = val[0..117] + '...' end end # add to table table.rows.push [k, val] end # output TTM.puts table.to_s end end |