Class: Johnny

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

Instance Method Summary collapse

Constructor Details

#initialize(dir = Dir.pwd) ⇒ Johnny

Returns a new instance of Johnny.



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

def initialize(dir=Dir.pwd)
  @source = File.expand_path(dir)
  @destination = File.join(@source, "html")
  
  @template = ERB.new(File.read(File.expand_path(File.join(File.dirname(__FILE__), "..", "templates", "default.html.erb"))))
  
  unless File.exists?(@destination) && File.directory?(@destination)
    Dir.mkdir(@destination)
  end
end

Instance Method Details

#handle(action, path) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/johnny.rb', line 18

def handle(action, path)
  if [".md", ".mdown", ".markdown"].include?(File.extname(path))
    source = File.join(@source, path)
    target = File.join(@destination, "#{File.basename(path, File.extname(path))}.html")
    action = "handle_#{action}"
    
    if self.respond_to?(action)
      self.send(action, source, target)
    end
  end
end

#handle_create(source, target) ⇒ Object



31
32
33
34
35
36
# File 'lib/johnny.rb', line 31

def handle_create(source, target)
  parse(source, target)
  puts "Create: #{target}"
  
  return true
end

#handle_delete(source, target) ⇒ Object



45
46
47
48
49
50
# File 'lib/johnny.rb', line 45

def handle_delete(source, target)
  if File.exists?(target)
    puts "Deleted: #{target}"
    File.delete(target)
  end
end

#handle_update(source, target) ⇒ Object



38
39
40
41
42
43
# File 'lib/johnny.rb', line 38

def handle_update(source, target)
  parse(source, target)
  puts "Update: #{target}"
  
  return true
end

#parse(source, target) ⇒ Object



68
69
70
71
72
73
74
75
76
77
# File 'lib/johnny.rb', line 68

def parse(source, target)
  File.open("#{target}", "w+") {|f|
    f.write(@template.result(ERBTemplate.new(
      File.basename(source, File.extname(source)),
      RDiscount.new(File.read(source)).to_html
    ).getBinding))
  }
  
  return nil
end

#run!Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/johnny.rb', line 52

def run!
  # this is something I'd expect in javascript, not ruby.
  johnny = self
  
  puts "Watching directory for changes to files..."
  puts "-> Parsed files will be placed in: #{File.join(Dir.pwd, "html")}"
  
  FSSM.monitor(@source, "**/*.*") do
    update {|base, relative| johnny.handle("update", relative) }
    delete {|base, relative| johnny.handle("delete", relative) }
    create {|base, relative| johnny.handle("create", relative) }
  end
  
  return
end