Ruby Sinatra存储变量

时间:2016-02-05 18:50:30

标签: ruby hyperlink routes sinatra

在下面的代码中,初始获取' /'包含一个表单,其行为是' /'。当用户输入一个数字时,它应该被转换为一个用于调用Game类的变量,为此我已经生成了另一个动作来在get' / game'中显示一个新表单。不存储post方法中生成的变量。我怎样才能存储在post中创建的变量,然后链接到get' / game'行动?

require 'sinatra'
require 'sinatra/reloader'
@@count = 5
Dict = File.open("enable.txt")

class Game
   attr_accessor :letters, :number, :guess, :disp
   @@count = 5

   def initialize (number)
     letters = find(number) 
   end

   def find (n)
     words =[]
     dictionary = File.read(Dict)  
     dictionary.scan(/\w+/).each {|word| words << word if word.length == n}
     letters = words.sample.split("").to_a 
     letters
   end

   def counter
         if letters.include?guess
            correct = check_guess(guess, letters)
          else
           @@count -= 1
          end
   end
end

get '/' do 
   erb :index
end

post '/' do 
  n = params['number'].to_i
  @letters = Game.new(n) 
  redirect '/game' 
end

get "/game" do 


   guess = params['guess']
   letters = @letters
   if guess != nil
     correct = check_guess(guess, letters)
   end
   disp = display(letters, correct)          

   erb :game, :locals => {:letters => letters, :disp => disp}  

end



   def display(letters, correct)
     line = "__"
     d=[]
     letters.each do |x| 
       if correct == nil
         d << line
       elsif correct.include?x  
         d << x  
       else
         d << line
       end
     end
     d.join(" ")
   end 


   def check_guess(guess, letters)
     correct = [] 
     if guess != nil   
       if letters.include?guess
         correct << guess
       end
     end
     correct
   end

1 个答案:

答案 0 :(得分:0)

你不能这样做:

@letters = Game.new(n)

每次创建请求时,都会创建新的Request实例,因此@letters属性不再存在。

相当于

r = Request.new()
r.letters = Game.new()

r = Request.new()
r.letters  # not defined anymore!!

您可以使用类变量

来实现您想要的效果
@@letters = Game.new(n)

虽然当您拥有多个用户时这将成为一场噩梦,但只有在您拥有单个ruby服务器进程时才会工作。

更高级的方法是将params['number']存储在会话cookie或数据库中。