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

레일스로 코딩 배우기

나는 루비가 코딩을 배우기에 좋은 출발점이라고 생각한다 Learn To Program 이라는 책을 읽어보라 https://pine.fm/LearnToProgram/ 물론 어느 programming language 로 시작하든지 코딩을 배우는 것은 인생에서 매우 중요하다고 생각한다 그리고 루비를 배우기에는 레일스가 좋은 출발점이라고 생각한다 지금 시작해보자 rails new app_name cd app_name 레일스의... Continue →