How to transform a user input in rails 4?

2019-09-03 12:24发布

问题:

I am creating an app where users could enter their name that will be returned as chemical symbols (when matching).

So I managed to do in the console like:

symbols = {
 "ac" => "Ac",
 "al" => "Al",
 "am" => "Al",
 "br" => "Br",
 "ba" => "Ba",
 "cr" => "Cr"
}

puts "Get your chemical name!"
name = gets.chomp
name.gsub!(/#{symbols.keys.join('|')}/, symbols)
puts name

Now I'd like to make it works in the app but I don't know how to create the method ? I want it to be displayed only in the views/show

= @convertor.name

= link_to 'Edit', edit_convertor_path(@convertor)
= link_to 'Back', convertors_path

shall I create the method in my model or else where?

class Convertor < ActiveRecord::Base
  def get_chemical_name(name)
    symbols = {
     "ac" => "Ac",
     "al" => "Al",
     "am" => "Al",
     "br" => "Br",
     "ba" => "Ba",
     "cr" => "Cr"
   }
    name.gsub!(/#{symbols.keys.join('|')}/, symbols)
    puts  name
  end
end

so in my view showI tried something like =@convertor.get_chemical(name) but unsuccessful.. I need your help please

回答1:

Yes, the method can stay in the model.

Short one:

@convertor.get_chemical(@convertor.name)

would work but this is not a right way to do that.

Correct way would be to change the method in Convertor class to not accept any arguments, since it is an instance method and it already has access to name attribute. So, after changing the method signature

  def get_chemical_name
    symbols = {
      "ac" => "Ac",
      "al" => "Al",
      "am" => "Al",
      "br" => "Br",
      "ba" => "Ba",
      "cr" => "Cr"
   }
    name.gsub!(/#{symbols.keys.join('|')}/, symbols)
  end

you will be able to use

=@convertor.get_chemical_name

Also, I removed useless puts name from the method definition - in Ruby the last evaluated line is already a return value of the method (unless returned before the end of the method).

Also, if by any chance you are using the symbols hash anywhere else, you can move it to constant.