2016-04-27 56 views
1

我正在檢查pry和Rails控制檯中的ActiveRecord對象,但其中一個屬性非常冗長。在Rails 4中檢查詳細的ActiveRecord對象

my_record.document.to_s.length # => 45480 

如何我可以查看記錄,以省略號截斷之前告訴Rails的,我只是想從my_record.document幾十個字符?

回答

2

您可以使用操作視圖中的truncate方法來執行此操作。例如,如果要截斷爲300個字符(包括省略號),則可以執行以下操作。

truncate(my_record.document.to_s, length: 300) 

你首先必須包括爲了在您的控制檯truncate可用::的ActionView的輔助方法。

include ActionView::Helpers 

這也是微不足道的純Ruby做,如果你想要去的路線:

max_length = 10 
"This could be a really long string".first(max_length - 3).ljust(max_length, "...") 

輸出:

"This co..." 

編輯

如果你想截斷單個屬性的檢查覆蓋attribute_for_inspect

舉例來說,你可以截斷document列的顯示,以300個字符(包括省略號)如下:

在你的模型:

def attribute_for_inspect(attr_name) 
    if attr_name.to_sym == :document 
    max_length = 300 
    value = read_attribute(attr_name).to_s 

    # You should guard against nil here. 
    value.first(max_length - 3).ljust(max_length, "...") 
    else 
    super 
    end 
end 

attr_for_inspectActiveRecord::AttributeMethods如果定義你想看看它是如何工作的:https://github.com/rails/rails/blob/52ce6ece8c8f74064bb64e0a0b1ddd83092718e1/activerecord/lib/active_record/attribute_methods.rb#L296