Class: ShowCode::Code

Inherits:
Object
  • Object
show all
Defined in:
lib/show_code/code.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(location) ⇒ Code

Returns a new instance of Code.



7
8
9
10
11
12
13
14
15
16
# File 'lib/show_code/code.rb', line 7

def initialize(location)
  @file         = location.file
  @line         = location.line
  file_lines    = File.readlines(@file) if @file

  related_lines = file_lines[(@line - 1)..-1] || []
  codes         = extract_method_code related_lines
  @lines        = codes.count
  @content      = codes.join
end

Instance Attribute Details

#contentObject (readonly)

Returns the value of attribute content.



5
6
7
# File 'lib/show_code/code.rb', line 5

def content
  @content
end

#fileObject (readonly)

Returns the value of attribute file.



5
6
7
# File 'lib/show_code/code.rb', line 5

def file
  @file
end

#lineObject (readonly)

Returns the value of attribute line.



5
6
7
# File 'lib/show_code/code.rb', line 5

def line
  @line
end

#linesObject (readonly)

Returns the value of attribute lines.



5
6
7
# File 'lib/show_code/code.rb', line 5

def lines
  @lines
end

#ownerObject (readonly)

Returns the value of attribute owner.



5
6
7
# File 'lib/show_code/code.rb', line 5

def owner
  @owner
end

Instance Method Details

#add_line_numbers(output) ⇒ Object



48
49
50
51
52
53
54
# File 'lib/show_code/code.rb', line 48

def add_line_numbers(output)
  line_number = line - 1
  output.split("\n").map do |loc|
    line_number += 1
    "\e[33m%i\e[0m #{loc}" % line_number
  end.join("\n")
end

#expression_end?(codes) ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/show_code/code.rb', line 28

def expression_end?(codes)
  str = codes.join

  catch(:valid) do
    eval("BEGIN{throw :valid}; #{str}")
  end

  # skip , or \
  str !~ /[,\\]\s*\z/
rescue SyntaxException
  false
end

#extract_method_code(related_lines) ⇒ Object

Raises:

  • (SyntaxError)


18
19
20
21
22
23
24
25
# File 'lib/show_code/code.rb', line 18

def extract_method_code(related_lines)
  codes = []
  related_lines.each do |loc|
    codes << loc
    return codes if expression_end?(codes)
  end
  raise SyntaxError, "unexpected $end"
end

#greetObject

Example: ShowCode ‘ShowCode::Code.new.greet’



57
58
59
# File 'lib/show_code/code.rb', line 57

def greet
  puts 'Hello ShowCode!'
end

#highlighted(opts = {}) ⇒ Object



41
42
43
44
45
46
# File 'lib/show_code/code.rb', line 41

def highlighted(opts = {})
  options = {:line_numbers => true}.merge(opts)
  colorized = CodeRay.scan(content, :ruby).tty
  output = options[:line_numbers] ? add_line_numbers(colorized) : colorized
  "\n%s\n\n" % output
end