Ruby Building Web Apps with Sinatra Updating Data A Route for PUT Requests

Peter Buckwalter
PRO
Peter Buckwalter
Pro Student 6,846 Points

Issues with Sinatra wiki app edit stage

Ok so when I update my page it seems to create a new page "%.txt" with the changes rather than actually editing the original page??

I also noticed that if I enter the page title capitalised in the browser it show it capitalised. If I enter it in lowercase I get it in lowercase. ???

require "sinatra"
require "uri"

def page_content(title)
  File.read("pages/#{title}.txt")
rescue Errno::ENOENT
  return nil
end

def save_content(title, content)
  File.open("pages/#{title}.txt", "w") do |file|
    file.print(content)
  end
end

get "/" do
  erb :welcome
end

get "/new" do
  erb :new
end

get "/:title" do
  @title = params[:title]
  @content = page_content(@title)
  erb :show
end

get "/:title/edit" do
  @title = params[:title]
  @content = page_content(@title)
  erb :edit
end

post "/create" do
  save_content(params["title"], params["content"])
  redirect URI.escape("/#{params["title"]}")
end

put "/:title" do
  save_content(params["title"], params["content"])
  redirect URI.escape("/#{params["title"]}")
end

2 Answers

Jay McGavren
STAFF
Jay McGavren
Treehouse Teacher

Your wiki.rb code looks good as far as I can tell. The error is probably in your edit.erb file, which I can't see. There is probably an error in its handling of the title form field.

I also noticed that if I enter the page title capitalised in the browser it show it capitalised. If I enter it in lowercase I get it in lowercase. ???

That's as expected - we're not manipulating the case of the titles at all. On a case-sensitive file system (which some operating systems have, and others don't) it might even create two separate .txt files. If this is an issue, you might want to look into the downcase instance method on Ruby's String class.

Peter Buckwalter
PRO
Peter Buckwalter
Pro Student 6,846 Points

Thanks Jay,

I got this sorted after after I set up a head against keyboard action and ran that for a while. It was a couple of typos here and there.

Thanks for getting back to me though.