1 minute read

1. Create Rails

rails new APP_NAME

2. Create Files

sytax : rails generate controller name_of_controller name_of_method Then all the files will be complete on the file. Magic!

rails generate controller menus create update

3. Change the routes

1) Method purpose - GET/POST 2) directory name (http://something.com/new) 3) to controller name # method name 4) call as short name (using ‘as’ make it easier that creating link)

Rails.application.routes.draw do
  get 'new', to: 'games#new', as: :new
  post 'score', to: 'games#score', as: :score
end
# <%= link_to "Play again", new_path %>

In case of Root / home page

Rails.application.routes.draw do
  root 'home', to: 'games#home'
end

# <%= link to "home", root_path %>

DINAMIC segementation is also possible (for example : http://something.com/124)

Rails.application.routes.draw do
  get '/index', to: "flats#index", as: "index"
  get '/show/:id', to: "flats#show", as: "show"
end

# params[:id] = id_number

Sample

1) Route

Rails.application.routes.draw do
  get 'new', to: 'games#new', as: :new
  post 'score', to: 'games#score', as: :score
end

2) Controller

require 'open-uri'

class GamesController < ApplicationController

  def new
    @letters = []
    10.times { @letters << ("A".."Z").to_a.sample(1).join("") }
  end

  def score
    @letters = params[:letters].split("")
    @word = params[:word].upcase!
    @words = @word.split("")
    url = "https://wagon-dictionary.herokuapp.com/#{@word}"
    json = open(url).read
    @result = JSON.parse(json)

    if (@words - @letters).length > 0
      @answer = "#{@word} is not we show tto you... baboddong..."
    elsif @result["found"] == false
      @answer = "sorry but #{@word} is not a English word bro :("
    else
      @answer = "Congratulation #{@word} is word, score is #{@result["length"]} :D"
    end
  end
end

3) View

3.1 New HTML

<h1>New Games</h1>

<div class="cards">
    <% @letters.each do |letter| %>
    <div class="card"><p><%= letter %></p></div>
    <% end %>
</div>

<!-- app/views/pages/home.html.erb -->
<h3>What is the longest word you can find?</h3>
<form action="/score" method="post">
  <%= hidden_field_tag :authenticity_token, form_authenticity_token %>
  <input type="text" name="word" placeholder="Word">
  <input id = "letters" type="text" name="letters" value="<%= @letters.join %>">
  <input type="submit">
</form>

3.2 Score HTML

<h1>Games#score</h1>

<div class="answer">
  <%= @answer %>
</div>

<%= link_to "Play again", new_path %>

Categories:

Updated: