Class: Minimo::Base

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

Constant Summary collapse

NO_CONTENT_METHOD =
%w(DELETE PATCH PUT)
CREATED_METHOD =
%w(POST)
CONTENT_TYPE =
{
  json: 'application/json; charset=utf-8',
  xml: 'application/xml; charset=utf-8',
  text: 'application/text; charset=utf-8'
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBase

Returns a new instance of Base.



16
17
18
19
# File 'lib/minimo.rb', line 16

def initialize
  @headers = default_header
  @fixture_path = './response'.freeze
end

Instance Attribute Details

#fixture_path=(value) ⇒ Object

Sets the attribute fixture_path

Parameters:

  • value

    the value to set the attribute fixture_path to.



21
22
23
# File 'lib/minimo.rb', line 21

def fixture_path=(value)
  @fixture_path = value
end

#headersObject

Returns the value of attribute headers.



21
22
23
# File 'lib/minimo.rb', line 21

def headers
  @headers
end

#log_pathObject

Returns the value of attribute log_path.



21
22
23
# File 'lib/minimo.rb', line 21

def log_path
  @log_path
end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/minimo.rb', line 27

def call(env)
  response_body = []
  $stdout.sync = true

  @request = Rack::Request.new(env)
  verb = @request.request_method
  file_path = fixture_path(verb)

  response = Rack::Response.new do |r|
    r.status = status_code(verb)
  end

  CONTENT_TYPE.keys.push(nil).each do |ext|
    break if file_path.nil?
    separator = ext.nil? ? '' : '.'
    file = [file_path, ext].join(separator)
    if File.exist? file
      response_body << File.read(file)
      @headers['Content-Type'] = header_content_type(ext)
      break
    end
  end

  if response_body.empty?
    response.status = 404
    @headers['Content-Type'] = header_content_type(:text)
    response_body << "Oops! No route for #{verb} #{@request.path_info}"
  end

  @headers.map { |k,v| response.set_header(k,v) }
  response.write response_body.join("\n")

  if @log_dir
    logger = Minimo::Logger.new @log_dir
    msg = "#{verb} #{@request.path_info} #{env['SERVER_PROTOCOL']} #{response.status}"
    logger.write msg
  end

  response.finish
end

#set(key, value) ⇒ Object



23
24
25
# File 'lib/minimo.rb', line 23

def set(key, value)
  instance_variable_set "@#{key.to_s}", value
end

#versionObject



68
69
70
# File 'lib/minimo.rb', line 68

def version
  VERSION
end