Running Ruby script via web interface

I follow the Michael Hart Rails Tutorial , and I'm already in chapter seven. But I want to do something else right now, the textbook does not teach. I want to run a script file inside my webpage. How can i do this? I saw other posts here saying to use Sinatra, but since I am following this guide, I don’t think it is a good idea to use it because it can distinguish everything from the tutorial.

Here is a simple script that I want to run on my web page:

#Somando idades

def soma_vetor_excluindo(index,vet)   
    soma = 0   
    for i in 0..9
        if(i!=index)
            soma = soma + vet[i].to_i
        end   
    end   
    return soma 
end

def soma_vetor(vet)   
    soma = 0   
    for i in 0..9
        soma = soma + vet[i].to_i   
    end   
    return soma 
end

def maior_vetor(vet)   
    maior = 0   
    for i in 0..9
        if(maior < vet[i])
            maior = vet[i]
        end   
    end   
    return maior 
end

idades = (0..9).collect{rand(99)+1}

soma_idades = (0..9).collect{0} soma = 0

print "#{idades} \n"

for i in 0..9   
    soma_idades[i] = soma_vetor_excluindo(i,idades) 
end

print "#{soma_idades} \n"

div = soma_vetor(soma_idades) / 9

resp = div - maior_vetor(soma_idades)

puts "#{resp}"
+3
source share
2 answers

- soma_vetor_excluindo, soma_vetor, maior_vetor .., , , ajax, , .

, , MathController.rb soma_vetor_excluindo:

class MathController < ApplicationController
  def soma_vetor_excluindo
  end
  def soma_vetor
  end
  def maior_vetor
  end
end

, , , route, routes.rb - :

get 'math/soma_vetor_excluindo/:index/:vet', to 'math#soma_vetor_excluindo'
get 'math/soma_vetor/:vet', to 'math#soma_vetor'
get 'math/maior_vetor/:vet', to 'math#maior_vetor'

, localhost/math/soma_vetor_excluindo/1/2 URL-, , soma_vetor_excluindo, params[:index] params[:vet], script .

, , - .

+3

, script. script routes.rb - :

get 'scripts/your_script', to 'scripts#your_script

(app/scripts_controller.rb) :

class ScriptsController < ApplicationController
  #Somando idades

  def soma_vetor_excluindo(index,vet)   
    soma = 0   
    for i in 0..9
        if(i!=index)
            soma = soma + vet[i].to_i
        end   
    end   
    return soma 
  end

  def soma_vetor(vet)   
    soma = 0   
    for i in 0..9
        soma = soma + vet[i].to_i   
    end   
    return soma 
  end

  def maior_vetor(vet)   
    maior = 0   
    for i in 0..9
        if(maior < vet[i])
            maior = vet[i]
        end   
    end   
    return maior 
  end

  def your_script
    idades = (0..9).collect{rand(99)+1}
    soma_idades = (0..9).collect{0} 
    soma = 0

    answer = "#{idades} \n"
    for i in 0..9   
      soma_idades[i] = soma_vetor_excluindo(i,idades) 
    end

    answer << "#{soma_idades} \n"

    div = soma_vetor(soma_idades) / 9
    resp = div - maior_vetor(soma_idades)
    answer << "#{resp}"

    render(text: answer)
  end
end

scripts/your_script, script.

, .

0

All Articles