Module: RSpec::Paramz::PrettyPrint

Defined in:
lib/rspec/paramz/pretty_print.rb

Class Method Summary collapse

Class Method Details

.inspect(value, raw_value = true) ⇒ Object



4
5
6
7
8
9
10
11
12
13
# File 'lib/rspec/paramz/pretty_print.rb', line 4

def self.inspect(value, raw_value = true)
  case value
  when Hash
    subject(value)
  when Proc
    to_source(value)
  else
    raw_value ? value : value.inspect
  end
end

.subject(value) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rspec/paramz/pretty_print.rb', line 15

def self.subject(value)
  return value if value.keys != [:subject]

  _subject = value.values.first
  case _subject
  when Proc
    "subject #{to_source(_subject)}"
  when Hash
    subject_name  = _subject.keys.first
    subject_value = _subject.values.first

    case subject_value
    when Proc
      "subject(:#{subject_name}) #{to_source(subject_value)}"
    else
      "subject { #{subject_value} }"
    end
  else
    value
  end
end

.to_source(value) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rspec/paramz/pretty_print.rb', line 37

def self.to_source(value)
  return value if value.is_a?(NamedProc) || !value.is_a?(Proc)

  node = RubyVM::AbstractSyntaxTree.of(value)
  return value if node.nil?

  path = value.source_location.first
  lines = File.readlines(path)
  source_lines = lines[(node.first_lineno - 1)..(node.last_lineno - 1)]
  source_lines[-1] = source_lines[-1][0..(node.last_column - 1)]
  source_lines[0]  = source_lines[0][node.first_column..]
  source_lines.map(&:strip).join("\n")
end