Class: Lux::Response

Inherits:
Object show all
Defined in:
lib/lux/response/response.rb

Overview

response.header ‘x-blah’, 123 response.max_age = 10 response.public = true response.status = 500

Defined Under Namespace

Classes: Flash, Header

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeResponse

Returns a new instance of Response.



13
14
15
16
17
# File 'lib/lux/response/response.rb', line 13

def initialize
  @render_start = Time.monotonic
  @headers      = Lux::Response::Header.new
  @max_age      = 0
end

Instance Attribute Details

#body(what = nil) ⇒ Object Also known as: body=

Returns the value of attribute body.



11
12
13
# File 'lib/lux/response/response.rb', line 11

def body
  @body
end

#content_type(type = nil) ⇒ Object

Returns the value of attribute content_type.



11
12
13
# File 'lib/lux/response/response.rb', line 11

def content_type
  @content_type
end

Returns the value of attribute cookie_domain.



11
12
13
# File 'lib/lux/response/response.rb', line 11

def cookie_domain
  @cookie_domain
end

Returns the value of attribute cookie_multidomain.



11
12
13
# File 'lib/lux/response/response.rb', line 11

def cookie_multidomain
  @cookie_multidomain
end

#cookiesObject

Returns the value of attribute cookies.



11
12
13
# File 'lib/lux/response/response.rb', line 11

def cookies
  @cookies
end

#headersObject

Returns the value of attribute headers.



11
12
13
# File 'lib/lux/response/response.rb', line 11

def headers
  @headers
end

#max_ageObject

define in seconds, how long should page be accessible in client cache if defined, cache becomes public and can be cache by proxies use with care.only for static resources and



9
10
11
# File 'lib/lux/response/response.rb', line 9

def max_age
  @max_age
end

#status(num = nil) ⇒ Object Also known as: status=

Returns the value of attribute status.



11
12
13
# File 'lib/lux/response/response.rb', line 11

def status
  @status
end

Instance Method Details

#auth(relam = nil) ⇒ Object

auth { |user, pass| [user, pass] == [‘foo’, ‘bar’] }



127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/lux/response/response.rb', line 127

def auth relam=nil
  if auth = current.request.env['HTTP_AUTHORIZATION']
    credentials = auth.to_s.split('Basic ', 2)[1].unpack("m*").first.split(':', 2)
    return true if yield *credentials
  end

  status 401
  header('WWW-Authenticate', 'Basic realm="%s"' % relam.or('default'))
  body = ErrorCell.unauthorized('HTTP 401 Authorization needed')

  false
end

#body!(what) ⇒ Object



79
80
81
# File 'lib/lux/response/response.rb', line 79

def body! what
  @body = what
end

#currentObject



19
20
21
# File 'lib/lux/response/response.rb', line 19

def current
  Lux.current
end

#etag(*args) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/lux/response/response.rb', line 32

def etag *args
  unless @headers['etag']
    args.push current.request.url

    key = '"%s"' % Lux.cache.generate_key(args)
    key = 'W/%s' % key unless max_age > 0

    @headers['etag'] = key
  end

  if current.request.env['HTTP_IF_NONE_MATCH'] == @headers['etag']
    @status = 304
    @body   = 'not-modified'
    true
  else
    false
  end
end

#flash(message = nil) ⇒ Object



102
103
104
105
106
# File 'lib/lux/response/response.rb', line 102

def flash message=nil
  @flash ||= Flash.new current.session[:lux_flash]

  message ? @flash.error(message) : @flash
end

#halt(status = nil, msg = nil) ⇒ Object



60
61
62
63
64
65
# File 'lib/lux/response/response.rb', line 60

def halt status=nil, msg=nil
  @status = status || 400
  @body   = msg if msg

  throw :done
end

#header(name, value = :_) ⇒ Object



23
24
25
26
# File 'lib/lux/response/response.rb', line 23

def header name, value=:_
  @headers[name] = value if value != :_
  @headers[name]
end

#permanent_redirect(where) ⇒ Object



122
123
124
# File 'lib/lux/response/response.rb', line 122

def permanent_redirect where
  redirect where, status:301
end

#redirect(where = nil, opts = {}) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/lux/response/response.rb', line 108

def redirect where=nil, opts={}
  return @headers['location'] unless where

  @status = opts.delete(:status) || 302
  opts.map { |k,v| flash.send(k, v) }

  @headers['location']   = where.index('//') ? where : "#{current.host}#{where}"
  @headers['access-control-expose-headers'] ||= 'Location'

  @body = %[redirecting to #{@headers['location']}\n\n#{opts.values.join("\n")}]

  throw :done
end

#renderObject



227
228
229
230
231
232
233
234
235
# File 'lib/lux/response/response.rb', line 227

def render
  Lux.log "\n#{current.request.request_method.white} #{Lux.current.request.path.white}"

  Lux::Config.live_require_check! if Lux.config(:auto_code_reload)

  Lux::Application.new.main

  write_response
end

#write_responseObject



211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/lux/response/response.rb', line 211

def write_response
  write_response_body
  write_response_header

  @status ||= 200
  Lux.log " #{@status}, #{@headers['x-lux-speed']}"

  if ENV['LUX_PRINT_ROUTES']
    print '* Finished route print '
    puts @status == 404 ? 'without a match'.red : 'with a match'.green
    exit
  end

  [@status, @headers.to_h, [@body]]
end

#write_response_bodyObject



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/lux/response/response.rb', line 140

def write_response_body
  unless @body
    @status = 404
    @body = Lux.error 'Document not found'
  end

  # respond as JSON if we recive hash
  if @body.kind_of?(Hash)
    @body = Lux.dev? ? JSON.pretty_generate(@body) : JSON.generate(@body)

    if current.request.params[:callback]
      @body = "#{current.request.params[:callback]}(#{ret})"
      @content_type ||= 'text/javascript'
    else
      @content_type ||= 'application/json'
    end

    @body += "\n"
  else
    # if somebody sets @content_type, respect that
    @body = @body.to_s unless @body.kind_of?(String)
    @content_type ||= 'text/plain' if @body[0,1] != '<'
    @content_type ||= 'text/html'
  end
end

#write_response_headerObject



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/lux/response/response.rb', line 166

def write_response_header
  domain =
    if cookie_domain
      cookie_domain
    elsif cookie_multidomain && current.domain.index('.')
      ".#{current.domain}"
    else
      current.request.host
    end

  # cache-control
  @headers['cache-control'] ||= Proc.new do
    cc      = ['max-age=%d' % max_age]

    if max_age > 0
      cc.push 'public, no-cache'
    else
      cc.push 'private, must-revalidate'
    end

    cc.join(', ')
  end.call

  current.session[:lux_flash] = flash.to_h

  # dont annd cookies to public pages (images, etc..)
  add_cookies = true
  add_cookies = false if @headers['cache-control'].index('public')

  if add_cookies
    encrypted = Crypt.encrypt(current.session.to_json)

    if current.cookies[Lux.config.session_cookie_name] != encrypted
      @headers['set-cookie']  = "#{Lux.config.session_cookie_name}=#{encrypted}; Expires=#{(Time.now+1.month).utc}; Path=/; Domain=#{domain};"
    end
  end

  etag(@body) if current.request.request_method == 'GET'

  @headers['x-lux-speed']     = "#{((Time.monotonic - @render_start)*1000).round(1)} ms"
  @headers['content-type']  ||= "#{@content_type}; charset=utf-8"
  @headers['content-length']  = @body.bytesize
  # if "no-store" is present then HTTP_IF_NONE_MATCH is not sent from browser
end