mercredi 18 mai 2022

Initializer doesn't create instance in console

I am new to ruby and I am trying to create a hangman game, to do so I need to create a new game each time the user click on a button.

First step is to create the same object each time the methode create will be called (it will be different because of the .sample.

I am trying to create an object with the initialize method in my model.rbfile.

Here is my code :

class Game < ApplicationRecord

  has_many :guesses

  def initialize(*)
    super
    @word_to_guess = word_to_guess
    @health_bar = 5
    @game_status = game_status
  end

  def word_to_guess
    words = [
      "spokesperson", "firefighter", "headquarters", "confession", "difficulty", "attachment", "mechanical",
      "accumulation", "hypothesis", "systematic", "attraction", "distribute", "dependence", "environment",
      "jurisdiction", "demonstrator", "constitution", "constraint", "consumption", "presidency", "incredible",
      "miscarriage", "foundation", "photography", "constituency", "experienced", "background", "obligation",
      "diplomatic", "discrimination", "entertainment", "grandmother", "girlfriend", "conversation", "convulsion",
      "constellation", "leadership", "insistence", "projection", "transparent", "researcher", "reasonable","continental",
      "excavation", "opposition", "interactive", "pedestrian", "announcement", "charismatic", "strikebreaker",
      "resolution", "professional", "commemorate", "disability", "collection", "cooperation", "embarrassment",
      "contradiction", "unpleasant", "retirement", "conscience", "satisfaction", "acquaintance", "expression",
      "difference", "unfortunate", "accountant", "information", "fastidious", "conglomerate", "shareholder",
      "accessible", "advertising", "battlefield", "laboratory", "manufacturer", "acquisition", "operational",
      "expenditure", "fashionable", "allocation", "complication", "censorship", "population", "withdrawal",
      "sensitivity", "exaggerate", "transmission", "philosophy", "memorandum", "superintendent", "responsibility",
      "extraterrestrial", "hypothesize", "ghostwriter", "representative", "rehabilitation", "disappointment",
      "understanding", "supplementary", "preoccupation"
          ]
    words.sample
  end

  def game_status
    game_status = ["Game not started yet", "In Game", "You win", "You loose"]
    game_status[0]
  end

end

The problem is that when I do a Game.new in console, it returns :

[1] pry(main)> Game.new
=> #<Game:0x00007fa79b613290 id: nil, word_to_guess: nil, health_bar: nil, created_at: nil, updated_at: nil, guesse_id: nil, game_status: nil>

So the instance is not created and I don't know why.

Aucun commentaire:

Enregistrer un commentaire