西纳特拉不知道这个小曲

时间:2017-06-27 00:39:08

标签: ruby sinatra

有人会检查我是否做错了吗?

我的app.rb:

require 'sinatra/base'
require 'sinatra/flash'
require './lib/hangperson_game.rb'

class HangpersonApp < Sinatra::Base
  enable :sessions
  register Sinatra::Flash

  before do
    @game = session[:game] || HangpersonGame.new('')
  end

  after do
    session[:game] = @game
  end

  get '/' do
    redirect '/new'
  end

  get '/new' do
    erb :new
    #"Hello World!"
  end

  post '/create' do
    @game = HangpersonGame.new(word)
    redirect '/show'
  end

  post '/guess' do
    letter = params[:guess].to_s[0]
    begin
      if letter.nil? || letter.empty? || !((letter=~/^[A-z]$/) == 0)
        flash[:message] = "Invalid guess." 
      elsif !(@game.guess(letter))
        flash[:message] = "You have already used that letter."
      end
    end
    redirect '/show'
  end

  get '/show' do
    ### YOUR CODE HERE ###
    if (@game.check_win_or_lose == :win)
      redirect '/win'
    elsif (@game.check_win_or_lose == :lose)
      redirect '/lose'
    else
      erb :show 
    end
  end

  get '/win' do
    ### YOUR CODE HERE ###
    if (@game.check_win_or_lose != :win)
      redirect '/show'
    else
      erb :win 
    end
  end

  get '/lose' do
    if (@game.check_win_or_lose != :lose)
      redirect '/show'
    else
      erb :lose 
    end
  end
end

2 个答案:

答案 0 :(得分:1)

问题是您没有向action提供任何form(即 url ),因此当您点击New Game按钮时,它会发送信息回复给自己,即new行动,但使用POST代替GET,从而为您提供错误。

action视图中的表单中添加您需要的/create(我假设为new),如下所示:

<form method="post" action="/create">
  <input type="submit" value="New Game"/>
</form>

这样,点击New Game后,表单就会发送到create行动。

答案 1 :(得分:0)

如果您创建模块化样式的Sinatra应用程序(可以read about it here),则应在类的END(在其内部)中声明此行:

run! if app_file == $0

现在您可以使用ruby my_modular/application.rb以及rackup -p 4567来运行应用程序