Module: JsonTruncate

Defined in:
lib/json_truncate/version.rb,
lib/json_truncate/truncate.rb

Constant Summary collapse

VERSION =
'0.0.1'

Class Method Summary collapse

Class Method Details

.process(object, opts, depth = 0) ⇒ Object



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
# File 'lib/json_truncate/truncate.rb', line 6

def self.process(object, opts, depth = 0)
    depth += 1

    if opts[:max_array_length] && object.is_a?(Array) && object.length > opts[:max_array_length]
        object.slice!(opts[:max_array_length]..-1)
        object.push('...')
    end

    if opts[:max_string_length] && object.is_a?(String) && object.length > opts[:max_string_length]
        object.slice!(opts[:max_string_length]..-1)
        object << '...'
    end

    if opts[:max_depth] && depth > opts[:max_depth] && [ Array, Hash ].include?(object.class)
        object.delete_if { |_| true }
    end

    if object.is_a?(Hash)
        object.each do |k,v|
            process(v, opts, depth)
        end
    elsif object.is_a?(Array)
        object.each do |v|
            process(v, opts, depth)
        end
    end

    object
end

.truncate(object, opts = {}) ⇒ Object



2
3
4
# File 'lib/json_truncate/truncate.rb', line 2

def self.truncate(object, opts = {})
    process(object.dup, opts)
end