Last active
August 29, 2015 14:17
-
-
Save proudlygeek/d8da596c17d3dd772db9 to your computer and use it in GitHub Desktop.
Ruby Datamapper + Sinatra PUT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| source 'https://rubygems.org' | |
| gem 'sinatra' | |
| gem 'thin' | |
| gem 'data_mapper' | |
| gem 'dm-sqlite-adapter' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'sinatra' | |
| require 'json' | |
| require 'pp' | |
| require_relative './user' | |
| get '/' do | |
| content_type 'text/html' | |
| [ | |
| '<ul>', | |
| User.all.map { |x| "<li><strong>#{x.id}</strong> | #{x.name} | #{x.notes}</li>" }, | |
| '</ul>' | |
| ].join() | |
| end | |
| put '/users/:id' do | |
| user = User.get(params[:id]) || halt(404, { error: "No such user id."}.to_json) | |
| body = JSON.parse request.body.read | |
| body.each do |key, value| | |
| user[key] = value | |
| if (user.save) | |
| # Read PUT ~> http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html | |
| status 301 | |
| end | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'data_mapper' | |
| DataMapper::Logger.new($stdout, :debug) | |
| DataMapper.setup(:default, 'sqlite:///Users/Bargelli/Code/sinatra-users/project.db') | |
| class User | |
| include DataMapper::Resource | |
| property :id, Serial | |
| property :name, String | |
| property :notes, Text | |
| property :created_at, DateTime | |
| end | |
| DataMapper.finalize | |
| # DataMapper.auto_migrate! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment