Class: StaticMatic::Server

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(staticmatic, default = nil) ⇒ Server

Returns a new instance of Server.



3
4
5
6
7
8
# File 'lib/staticmatic/server.rb', line 3

def initialize(staticmatic, default = nil)
  @files = default || Rack::File.new(staticmatic.site_dir)
  @staticmatic = staticmatic
  

end

Class Method Details

.start(staticmatic) ⇒ Object

Starts the StaticMatic preview server



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/staticmatic/server.rb', line 45

def self.start(staticmatic)
  [ 'INT', 'TERM' ].each do |signal|
    Signal.trap(signal) do
      puts 
      puts "Exiting"
      exit!(0)
    end
  end
  port = staticmatic.configuration.preview_server_port || 3000

  host = staticmatic.configuration.preview_server_host || ""

  app = Rack::Builder.new do
    use Rack::ShowExceptions
    run StaticMatic::Server.new(staticmatic)
  end 
  
  Rack::Handler::WEBrick.run(app, :Port => port, :Host => host)
end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/staticmatic/server.rb', line 10

def call(env)
  @staticmatic.load_helpers
  path_info = env["PATH_INFO"]

  file_dir, file_name, file_ext = expand_path(path_info)

  # remove stylesheets/ directory if applicable
  file_dir.gsub!(/^\/stylesheets\/?/, "")
  
  file_dir = CGI::unescape(file_dir)
  file_name = CGI::unescape(file_name)

  unless file_ext && ["html", "css"].include?(file_ext) &&
      @staticmatic.template_exists?(file_name, file_dir) &&
      File.basename(file_name) !~ /^\_/
    return @files.call(env)
  end

  res = Rack::Response.new
  res.header["Content-Type"] = "text/#{file_ext}"

  begin
    if file_ext == "css"
      res.write @staticmatic.generate_css(file_name, file_dir)
    else
      res.write @staticmatic.generate_html_with_layout(file_name, file_dir)
    end
  rescue StaticMatic::Error => e
    res.write e.message
  end

  res.finish
end