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
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/stasis/dev_mode.rb', line 10

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

  puts "\nDevelopment mode enabled: ".green + dir 
  $stdout.flush

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

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

  glob =
    Dir.chdir(@stasis.root) do
      # If destination is within root
      if @stasis.destination[0..@stasis.root.length] == "#{@stasis.root}/"
        relative = @stasis.destination[@stasis.root.length+1..-1] rescue nil
        Dir["*"].inject(["*"]) do |array, path|
          if File.directory?(path) && path != relative
            array.push("#{path}/**/*")
          end
          array
        end
      else
        [ "*", "**/*" ]
      end
    end

  dw = DirectoryWatcher.new(@stasis.root)
  dw.add_observer { render }
  dw.glob = glob
  dw.interval = 0.1
  dw.start

  if @options[:development].is_a?(::Integer)
    mime_types = WEBrick::HTTPUtils::DefaultMimeTypes

    additional_mime_types = @options[:mime_types]
    
    additional_mime_types.each do |extension, mimetype|
      mime_types.store extension, mimetype
      puts "add mime type #{mimetype} with extension .#{extension}"
    end

    mime_types.store 'js', 'application/javascript'

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

    server.start
  else
    loop { sleep 1 }
  end
end