Class: Stasis::DevMode

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

Instance Method Summary collapse

Constructor Details

#initialize(dir, options = {}) ⇒ DevMode

Returns a new instance of DevMode.



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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/stasis/dev_mode.rb', line 10

def initialize(dir, options={})
  trap("INT") { exit }

  puts "\nDevelopment mode enabled: #{dir}"
  $stdout.flush

  @dir = dir
  @options = options
  @options[:development] ||= true

  @stasis = Stasis.new(*[ @dir, @options[:public], @options ].compact)

  dw = DirectoryWatcher.new(@stasis.root)
  dw.interval = 0.1

  Dir.chdir(@stasis.root) do
    within_public = @stasis.destination[0..@stasis.root.length-1] == @stasis.root
    rel_public = @stasis.destination[@stasis.root.length+1..-1] rescue nil
    dw.glob = Dir["*"].inject(["*"]) do |array, path|
      if File.directory?(path) && (!within_public || path != rel_public)
        array << "#{path}/**/*"
      end
      array
    end
  end

  dw.add_observer { render }
  dw.start

  if options[:development].is_a?(::Integer)
    mime_types = WEBrick::HTTPUtils::DefaultMimeTypes
    mime_types.store 'js', 'application/javascript'
    
    outfile = (RUBY_PLATFORM =~ /mswin|mingw/) ? 'NUL:' : '/dev/null'
    server  = WEBrick::HTTPServer.new(
      :AccessLog => [ nil, nil ],
      :DocumentRoot => @stasis.destination,
      :Logger => WEBrick::Log.new(outfile),
      :MimeTypes => mime_types,
      :Port => options[:development]
    )
    
    ['INT', 'TERM'].each do |signal|
      trap(signal) { server.shutdown }
    end

    server.start
  else
    loop { sleep 1000 }
  end
end