buzzword bingo with Rails

I ran into “Integrating Elm with Rails 5.1” post on Pragmatic Studio blog a month ago.

And then I wanted to use this Rails setting while watching Pragmatic Studio Elm course. In the video, what is used was node server.js. I preferred not to understand how it works, so I did the same thing in Rails.

This is what we need at the lesson. It’s not other than just rendering JSON with 5 random buzzword entries in the back-end. For example:

[
  {
    id: 3,
    phrase: "In The Cloud",
    points: 300
  },
  {
    id: 8,
    phrase: "User-Centric",
    points: 175
  },
  {
    id: 2,
    phrase: "Doing Agile",
    points: 200
  },
  {
    id: 10,
    phrase: "Synergize",
    points: 375
  },
  {
    id: 4,
    phrase: "Rock-Star Ninja",
    points: 400
  }
]

In app/controllers/entries_controller.rb, following is what I did. This code is rendering 5 random entries as JSON.

class EntriesController < ApplicationController
  def random_entries
    @entries = Entry.order("RANDOM()").limit(5)
  end
end

We need more code, on top of the Integrating Elm with Rails 5.1. We need a route, and a table, as well as a controller.

config/routes.rb

  scope defaults: {format: :json} do
    get '/random-entries' => 'entries#random_entries'
  end

generate Entry model

rails generate model Entry phrase:string points:integer
rails db:migrate

And if you prefer, you can copy and paste this into your db/seeds.rb file. and run rails db:seed

Entry.create([
  {
    phrase: "Future-Proof",
    points: 100
  },
  {
    phrase: "Doing Agile",
    points: 200
  },
  {
    phrase: "In The Cloud",
    points: 300
  },
  {
    phrase: "Rock-Star Ninja",
    points: 400
  },
  {
    phrase: "Best of Breed",
    points: 150
  },
  {
    phrase: "Reactive",
    points: 250
  },
  {
    phrase: "Zero to Hero",
    points: 350
  },
  {
    phrase: "User-Centric",
    points: 175
  },
  {
    phrase: "Cross-Platform",
    points: 225
  },
  {
    phrase: "Synergize",
    points: 375
  },
])

Of course, you’re using Rails 5.1 – and you have read the great post on Pragmatic Studio blog, and taking their Building Web Apps with Elm course.

Ah, don’t forget. Elm code should be changed accordingly. Let us change getEntries command on app/javascript/packs/Bingo.elm file.

getEntries : Cmd Msg
getEntries =
    Http.send NewEntries (Http.get "/random-entries" (Decode.list entryDecoder))

… because it’s not a separate server (as like http://localhost:3000/random-entries) any more. I deployed with Heroku, and it was a very simple process.

 
0
Kudos
 
0
Kudos

Now read this

React with Ruby on Rails 5.1

$ ruby -v ruby 2.4.1p111 $ rails -v Rails 5.1.4 $ brew install yarn --without-node $ yarn -v 1.0.2 $ rails new scoreboard --webpack=react --api BOTH of two options. why not? https://yarnpkg.com/en/docs/install#alternatives-tab First let’... Continue →