Domanda

Using the Ruby Sinatra framework I have created two pages, 'home' and 'create'. My home page displays whatever is in the .txt file within my directory. In the 'create' page, I want a form that displays the existing .txt file and can be edited and saved so that the home page displays whoever updates the form (much like a wiki). How do I go about this?

The wiki.rb currently reads:

get '/' do
  @logfile = File.open("logfile.txt","r")
  erb :home
end

get '/create' do
  # I do not know what to put here
end

And my erb's read:

home:

<h2>Content:</h2>
<% @logfile.each_line do |line| %>
<%= line %>
<% end %>

create:

<h2>Edit your content:</h2>
<form action="/" method="post">
#I know I have to embed the logfile here somewhere?  
Content:<input type="textarea" name="content"><br>
<input type="submit" value="Save">  
</form>
È stato utile?

Soluzione

EDIT: Your methods would be like this

get '/create' do
    @logfile = File.open("logfile.txt","r")
    @contents = @logfile.read
    @logfile.close
    erb :create
end

post '/create' do
    @logfile = File.open("logfile.txt","w")
    @logfile.truncate(@logfile.size)
    @logfile.write(params[:file])
    @logfile.close
    redirect '/create'
end

Your create.erb would be like this

<form action="/create" method="post">
    <input type="text" name="file" value="<%= @contents %>">
    <input type="submit" value="Save">  
</form>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top