Oh!Coder

Coding Life

Awesome Print Gem简介

| Comments

今天介绍一个开发模式下常用的辅助类型的gem,名字叫Awesome Print

简介

Awesome Print能够非常漂亮的打印出Ruby对象,可以使用全彩色的样式打印出Ruby对象内部的结构。Rails的ActiveRecord对象以及Rails内部的template通过进行混合包含支持此功能。

安装

1
2
3
4
5
# Installing as Ruby gem
$ gem install awesome_print

# Cloning the repository
$ git clone git://github.com/michaeldv/awesome_print.git

基本使用

1
2
require "awesome_print"
ap object, options = {}

默认选项:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
:indent     => 4,      # Indent using 4 spaces.
:index      => true,   # Display array indices.
:html       => false,  # Use ANSI color codes rather than HTML.
:multiline  => true,   # Display in multiple lines.
:plain      => false,  # Use colors.
:raw        => false,  # Do not recursively format object instance variables.
:sort_keys  => false,  # Do not sort hash keys.
:limit      => false,  # Limit large output for arrays and hashes. Set to a boolean or integer.
:color => {
  :args       => :pale,
  :array      => :white,
  :bigdecimal => :blue,
  :class      => :yellow,
  :date       => :greenish,
  :falseclass => :red,
  :fixnum     => :blue,
  :float      => :blue,
  :hash       => :pale,
  :keyword    => :cyan,
  :method     => :purpleish,
  :nilclass   => :red,
  :rational   => :blue,
  :string     => :yellowish,
  :struct     => :pale,
  :symbol     => :cyanish,
  :time       => :greenish,
  :trueclass  => :green,
  :variable   => :cyanish
}

支持的颜色:

1
2
:gray, :red, :green, :yellow, :blue, :purple, :cyan, :white
:black, :redish, :greenish, :yellowish, :blueish, :purpleish, :cyanish, :pale

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
$ cat > 1.rb
require "awesome_print"
data = [ false, 42, %w(forty two), { :now => Time.now, :class => Time.now.class, :distance => 42e42 } ]
ap data
^D
$ ruby 1.rb
[
    [0] false,
    [1] 42,
    [2] [
        [0] "forty",
        [1] "two"
    ],
    [3] {
           :class => Time < Object,
             :now => Fri Apr 02 19:55:53 -0700 2010,
        :distance => 4.2e+43
    }
]

$ cat > 2.rb
require "awesome_print"
data = { :now => Time.now, :class => Time.now.class, :distance => 42e42 }
ap data, :indent => -2  # <-- Left align hash keys.
^D
$ ruby 2.rb
{
  :class    => Time < Object,
  :now      => Fri Apr 02 19:55:53 -0700 2010,
  :distance => 4.2e+43
}

$ cat > 3.rb
require "awesome_print"
data = [ false, 42, %w(forty two) ]
data << data  # <-- Nested array.
ap data, :multiline => false
^D
$ ruby 3.rb
[ false, 42, [ "forty", "two" ], [...] ]

$ cat > 4.rb
require "awesome_print"
class Hello
  def self.world(x, y, z = nil, &blk)
  end
end
ap Hello.methods - Class.methods
^D
$ ruby 4.rb
[
    [0] world(x, y, *z, &blk) Hello
]

$ cat > 5.rb
require "awesome_print"
ap (''.methods - Object.methods).grep(/!/)
^D
$ ruby 5.rb
[
    [ 0] capitalize!()           String
    [ 1]      chomp!(*arg1)      String
    [ 2]       chop!()           String
    [ 3]     delete!(*arg1)      String
    [ 4]   downcase!()           String
    [ 5]     encode!(*arg1)      String
    [ 6]       gsub!(*arg1)      String
    [ 7]     lstrip!()           String
    [ 8]       next!()           String
    [ 9]    reverse!()           String
    [10]     rstrip!()           String
    [11]      slice!(*arg1)      String
    [12]    squeeze!(*arg1)      String
    [13]      strip!()           String
    [14]        sub!(*arg1)      String
    [15]       succ!()           String
    [16]   swapcase!()           String
    [17]         tr!(arg1, arg2) String
    [18]       tr_s!(arg1, arg2) String
    [19]     upcase!()           String
]

$ cat > 6.rb
require "awesome_print"
ap 42 == ap(42)
^D
$ ruby 6.rb
42
true
$ cat 7.rb
require "awesome_print"
some_array = (1..1000).to_a
ap some_array, :limit => true
^D
$ ruby 7.rb
[
    [  0] 1,
    [  1] 2,
    [  2] 3,
    [  3] .. [996],
    [997] 998,
    [998] 999,
    [999] 1000
]

$ cat 8.rb
require "awesome_print"
some_array = (1..1000).to_a
ap some_array, :limit => 5
^D
$ ruby 8.rb
[
    [  0] 1,
    [  1] 2,
    [  2] .. [997],
    [998] 999,
    [999] 1000
]

例子(Rails console)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
$ rails console
rails> require "awesome_print"
rails> ap Account.limit(2).all
[
    [0] #<Account:0x1033220b8> {
                     :id => 1,
                :user_id => 5,
            :assigned_to => 7,
                   :name => "Hayes-DuBuque",
                 :access => "Public",
                :website => "http://www.hayesdubuque.com",
        :toll_free_phone => "1-800-932-6571",
                  :phone => "(111)549-5002",
                    :fax => "(349)415-2266",
             :deleted_at => nil,
             :created_at => Sat, 06 Mar 2010 09:46:10 UTC +00:00,
             :updated_at => Sat, 06 Mar 2010 16:33:10 UTC +00:00,
                  :email => "[email protected]",
        :background_info => nil
    },
    [1] #<Account:0x103321ff0> {
                     :id => 2,
                :user_id => 4,
            :assigned_to => 4,
                   :name => "Ziemann-Streich",
                 :access => "Public",
                :website => "http://www.ziemannstreich.com",
        :toll_free_phone => "1-800-871-0619",
                  :phone => "(042)056-1534",
                    :fax => "(106)017-8792",
             :deleted_at => nil,
             :created_at => Tue, 09 Feb 2010 13:32:10 UTC +00:00,
             :updated_at => Tue, 09 Feb 2010 20:05:01 UTC +00:00,
                  :email => "[email protected]",
        :background_info => nil
    }
]
rails> ap Account
class Account < ActiveRecord::Base {
                 :id => :integer,
            :user_id => :integer,
        :assigned_to => :integer,
               :name => :string,
             :access => :string,
            :website => :string,
    :toll_free_phone => :string,
              :phone => :string,
                :fax => :string,
         :deleted_at => :datetime,
         :created_at => :datetime,
         :updated_at => :datetime,
              :email => :string,
    :background_info => :string
}
rails>

与IRB整合

为了让awesome_print作为irb以及Rails console的默认格式,需要在~/.irbrc文件添加如下代码:

1
2
require "awesome_print"
AwesomePrint.irb!

与PRY整合

如果你很怀念awesome_print的输出格式,下面这种方法可以让你在pry中使用。在~/.pryrc中添加如下代码:

1
2
require "awesome_print"
AwesomePrint.pry!

作为Logger的便捷方法

awesome_print可以为Logger和ActiveSupport::BufferedLogger类添加’ap’方法,可以方便调用:

1
logger.ap object

默认情况下,log只能在开发层次中使用。你可以修改为全局模式:

1
:log_level => :info

自定义的默认模式下(如下)。你还可以对每个单独的调用进行覆盖:

1
logger.ap object, :warn

作为ActiveView的便捷方法

把awesome_print中的’ap’方法添加进ActionView::Base类中,让其在Rails template中能够使用。比如:

1
2
<%= ap @accounts.first %>   # ERB
!= ap @accounts.first       # HAML

使用其他web framework(比如:Sinatra的template)你可以明确的request HTML格式:

1
<%= ap @accounts.first, :html => true %>

自定义默认设置

通过在home目录创建.aprc文件,进行自定义的默认设置。在文件中可以对AwesomePrint.defaults进行默认设置。例如:

1
2
3
4
5
6
7
8
# ~/.aprc file.
AwesomePrint.defaults = {
  :indent => -2,
  :color => {
    :hash  => :pale,
    :class => :white
  }
}

版本路线

AwesomePrint跟随Semantic Versioning标准。

Comments