🎃

Reading text by Ruby on Rails and Javascript

2021/10/06に公開

Fetching easy api by javascript in same app .
We created text reading system with Paint content

routes.rb

namespace 'api' do
  resources :paints
end

controllers/api/paints.controller.rb

module Api
  class PaintsController < ApplicationController
    def index
      posts = Paint.all
      render json: { status: 'success', messge: 'Loaded paints', data: posts }
    end

    def show
      @paint = Paint.find(params[:id])
      render json: { status: 'success' , message: 'Loaded the paint', data: @paint }
    end
  end
end

index.html.erb

<% @paints.each do |paint| %>
   <button id="paint-button" class="speak-text-button" onclick="readText(event, <%= paint.id %>)">
       <i class="fas fa-headphones-alt"></i>
    </button>
<% end %>

reading-text.js

window.readText = async (event, id) => {
  if (!event || !id) return;
  event.preventDefault();

  const paint = await findOnePaint(id)
  speak(paint)
}
const findOnePaint = async (id) => {
  const res = await _fetch(id)
  const paint = await res.json();
  return paint.data;
}
const _fetch = async (id) => {
  try {
    const currentHost = location.hostname
    const apiUrlDev = `http://localhost:3000/api/paints/${id}`
    const apiUrlProd = `https://www.deep-recommend.com/api/paints/${id}`
    console.log({
      currentHost: currentHost
    })
    if (currentHost === 'localhost') {
      return await fetch(apiUrlDev);
    }
    if (currentHost === 'www.deep-recommend.com') {
      return await fetch(apiUrlProd);
    }
    if (currentHost === 'deep-recommened.com') {
      return await fetch(apiUrlProd);
    } 
  } catch (err) {
    console.error(err)
  }
}
const speak = (paint) => {
  const speak = new SpeechSynthesisUtterance();
  speak.text = paint.content
  speechSynthesis.speak(speak)
}

Discussion