Class: Murlsh::UrlServer
- Inherits:
-
Object
- Object
- Murlsh::UrlServer
- Includes:
- HeadFromGet
- Defined in:
- lib/murlsh/url_server.rb
Overview
Build responses for HTTP requests.
Instance Method Summary (collapse)
-
- (Object) get(req)
Respond to a GET request.
-
- (UrlServer) initialize(config)
constructor
A new instance of UrlServer.
-
- (Object) post(req)
Respond to a POST request.
Methods included from HeadFromGet
Constructor Details
- (UrlServer) initialize(config)
A new instance of UrlServer
11 |
# File 'lib/murlsh/url_server.rb', line 11 def initialize(config); @config = config; end |
Instance Method Details
- (Object) get(req)
Respond to a GET request. Return a page of urls based on the query string parameters.
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/murlsh/url_server.rb', line 15 def get(req) conditions = Murlsh::SearchConditions.new(req['q']).conditions page = [req['p'].to_i, 1].max per_page = req['pp'] ? req['pp'].to_i : @config.fetch('num_posts_page', 25) result_set = Murlsh::UrlResultSet.new(conditions, page, per_page) resp = Rack::Response.new resp['Content-Type'] = 'text/html; charset=utf-8' resp.body = Murlsh::UrlBody.new(@config, req, result_set, resp['Content-Type']) resp['Cache-Control'] = 'must-revalidate, max-age=0' resp['ETag'] = "\"#{resp.body.md5}\"" resp end |
- (Object) post(req)
Respond to a POST request. Add the new url and return json.
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 74 75 76 77 78 79 80 81 82 83 84 85 |
# File 'lib/murlsh/url_server.rb', line 36 def post(req) auth = req['auth'] if user = auth.empty? ? nil : Murlsh::Auth.new( @config.fetch('auth_file')).auth(auth) mu = Murlsh::Url.new do |u| u.url = req['url'] u.email = user[:email] u.name = user[:name] # optional parameters unless req['thumbnail'].to_s.empty? u.thumbnail_url = req['thumbnail'] end u.time = if req['time'] Time.at(req['time'].to_f).utc else Time.now.utc end unless req['title'].to_s.empty? u.title = req['title'] u.user_supplied_title = true end u.via = req['via'] unless req['via'].to_s.empty? end begin # validate before add_pre plugins have run and also after (in save!) raise ActiveRecord::RecordInvalid.new(mu) unless mu.valid? Murlsh::Plugin.hooks('add_pre') { |p| p.run mu, @config } mu.save! Murlsh::Plugin.hooks('add_post') { |p| p.run mu, @config } response_body, response_code = [mu], 200 rescue ActiveRecord::RecordInvalid => error response_body = { 'url' => error.record, 'errors' => error.record.errors, } response_code = 500 end else response_body, response_code = '', 403 end Rack::Response.new(response_body.to_json, response_code, { 'Content-Type' => 'application/json' }) end |