Danny Santos
Danny Santos

Reputation: 1160

Ruby - Retrieve a value from URL params

I'm completely new to this so you'll have to excuse my ignorance but I'm trying to pass a dynamic value into a function that gets the sum of all prime numbers up to a limit. I'm passing the dynamic limit through in the URL params but can't seem to make it work:

index.erb:

<form action="/primes">
  <input type="text" name="prime_limit" value="<%= @limit %>">
  <input type="submit" value="Get Primes">
</form>

app.rb:

get '/primes' do
  # TODO - Can we make this dynamic?
    limit = uri.params['prime_limit']

  # TODO - add your prime number solution in the primes.rb file.
  @sum = Primes.sum_to(limit)

  erb :primes, :layout => :main
end

primes.rb:

require 'uri'
require 'cgi'

uri = URI.parse(@object.location)
uri_params = CGI.parse(uri.query)

class Primes
  def self.sum_to(limit)
    # TODO - add your prime number solution here...
      require 'prime'
      Prime.each(limit).inject(:+)
  end
end

primes.erb:

<h1>Prime Numbers</h1>

Sum : <%= @sum %>

<div>
  <a href="/">Back</a>
</div>

Any help would be hugely appreciated.

Thanks

Upvotes: 0

Views: 760

Answers (1)

cozyconemotel
cozyconemotel

Reputation: 1161

Perhaps this example can help you? Just a minimal code that (I think) does what you want sinatra to do.. you get the idea

# app.rb
require 'sinatra'

get '/' do
    erb :index
end

get '/primes' do
    @sum = Primes.sum_to(params[:prime_limit].to_i)
    erb :primes
end

class Primes
  def self.sum_to(limit)
    # TODO - add your prime number solution here...
    require 'prime'
    Prime.each(limit).inject(:+)
  end
end

The params[] hash stores querystring and form data. So when you throw a GET request with querystrings that looks like example.com/app/?arg=3, params[:arg] is set to 3.

You could also do get '/app/:arg' do in sinatra, which makes /app/45 store params[:arg] = 45. Sinatra is a simple but powerful tool, and the documentations are not that long. I think it's worth looking through all or most of them.

Upvotes: 2

Related Questions