Victor Coelho
Victor Coelho

Reputation: 1

Pass Params from select_tag in rails to one script.rb get this params

Hello how is it possible to pass web parameters to an rb script in rails?

I'm using select_tag where when choosing an option I send the value to a variable in script.rb

Could help me I'm studying ruby ​​and rails is very complicated for me to do this.

my controller.rb

@myvalue = ["OPT VALUE 1","OPT VALUE 2"]

my external script.rb

loop do
  @give_my_param_from_rails = gets.chomp
  case @give_my_param_from_rails
  when '1'
    puts "i get number 1"
  when '2'
    puts "i get number 2"
  else
    puts "dont get any value"
    break
  end
end

my html.erb

<%= select_tag "my_options", options_for_select(@myvalue) %>

In my external script I want the rails value selected in select_tag to be set in the @give_my_param_from_rails variable help me?

Upvotes: 0

Views: 99

Answers (1)

3limin4t0r
3limin4t0r

Reputation: 21130

I've added $stdout.flush to the end of your script to flush the output for each line of input:

loop do
  line = gets.chomp

  case line
  when '1'
    puts "i get number 1"
  when '2'
    puts "i get number 2"
  else
    puts "dont get any value"
    break
  end

  $stdout.flush # flush output after each line of input
end

To access the script in your controller you can now do:

# allow writing to io by using r+ mode
# https://ruby-doc.org/core-2.6.5/IO.html#method-c-new-label-IO+Open+Mode
File.popen('ruby /path/to/script.rb', 'r+') do |io|
  io.puts params[:my_options] # assuming params[:my_options] is "1"
  io.gets #=> "i get number 1\n"
  io.puts 2
  io.gets #=> "i get number 2\n"
  io.puts "foo bar" # falling in the else scenario breaks the loop, exiting the script
  io.gets #=> "dont get any value\n"
  io.puts 1
  io.gets #=> nil
  io.puts "foo bar"
  io.gets #=> nil
end

If you only need to supply one input you could use backticks instead:

input = params[:my_options] # assuming params[:my_options] is "foo bar"
# escape special characters in double quoted context
# https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html
sanatized_input = input.gsub(/([$`\\"])/, '\\\\\1')
output = `echo "${sanatized_input}" | ruby /path/to/script.rb`
#=> "dont get any value\n"

Keep in mind that you don't handle the scenario where you supply 1 or 2 and then close the input. When this happens the next gets call will return nil.

`echo 1 | ruby /path/to/script.rb`
# script.rb:2:in `block in <main>': undefined method `chomp' for nil:NilClass (NoMethodError)
#   from script.rb:1:in `loop'
#   from script.rb:1:in `<main>'
#=> "i get number 1\n"

To resolve this you could do something like:

loop do
  line = gets or break # break the loop if gets returns nil
  line.chomp!

  # ...
end

Upvotes: 0

Related Questions