Class: VisualizeRuby::InputCoercer

Inherits:
Object
  • Object
show all
Defined in:
lib/visualize_ruby/input_coercer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input, name:) ⇒ InputCoercer

Returns a new instance of InputCoercer.



7
8
9
10
# File 'lib/visualize_ruby/input_coercer.rb', line 7

def initialize(input, name:)
  @input = input
  @name = name
end

Instance Attribute Details

#inputObject (readonly)

Returns the value of attribute input.



5
6
7
# File 'lib/visualize_ruby/input_coercer.rb', line 5

def input
  @input
end

#nameObject (readonly)

Returns the value of attribute name.



5
6
7
# File 'lib/visualize_ruby/input_coercer.rb', line 5

def name
  @name
end

Instance Method Details

#close!Object



36
37
38
# File 'lib/visualize_ruby/input_coercer.rb', line 36

def close!
  @temp_file.close! if @temp_file
end

#load_fileObject



49
50
51
# File 'lib/visualize_ruby/input_coercer.rb', line 49

def load_file
  load(to_file.path)
end

#readObject



25
26
27
28
29
30
31
32
33
34
# File 'lib/visualize_ruby/input_coercer.rb', line 25

def read
  case input
  when String
    input
  when File, Tempfile, Pathname
    to_file.read
  else
    raise ArgumentError, "#{name} was given an unknown type #{input.class}"
  end
end

#temp_fileObject



40
41
42
43
44
45
46
47
# File 'lib/visualize_ruby/input_coercer.rb', line 40

def temp_file
  @temp_file ||= begin
    file = Tempfile.new(%w(calling_code .rb))
    file.write(input)
    file.rewind
    file
  end
end

#to_fileObject



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/visualize_ruby/input_coercer.rb', line 12

def to_file
  @to_file ||= case input
               when File
                 input
               when Pathname
                 File.open(input)
               when String
                 temp_file
               else
                 raise ArgumentError, "#{name} was given an unknown type #{input.class}"
               end
end

#to_procObject



53
54
55
56
57
58
59
# File 'lib/visualize_ruby/input_coercer.rb', line 53

def to_proc
  if input.is_a?(Proc)
    input
  else
    Proc.new { load_file }
  end
end