将params [:thing]传递给另一个函数

时间:2022-06-05 16:02:53

So, i got the following code to parse a CSV file:

所以,我得到以下代码来解析CSV文件:

CSV.foreach(params[:file]) do |row|
    #bingbangbong
end

But I have two functions, one for show the CSV parsed file, and another one to save it on a db.

但是我有两个函数,一个用于显示CSV解析文件,另一个用于将其保存在数据库中。

My question is: How can I pass the params[:file] var to another function, something like this:

我的问题是:如何将params [:file] var传递给另一个函数,如下所示:

def show_CSV
    CSV.foreach(params[:file]) do |row|
        #Showing the parsed CSV
    end
end

def save_CSV
    CSV.foreach(params[:file]) do |row|
        #Showing the parsed CSV
    end
end

But, without making the user to upload the file again.

但是,没有让用户再次上传文件。

2 个解决方案

#1


2  

def show_and_save_CSV(options={})
  CSV.foreach(params[:file]) do |row|
    if options[:show]
      #Showing the parsed CSV
    end
    if options[:save]
      # save
    end
  end
end

Just remember that CSV.foreach loops through the lines of the provided file, so this way you will read the file just once.

请记住,CSV.foreach循环遍历所提供文件的行,因此这样您只需读取一次该文件。

def save_CSV
  show_and_save_CSV(:save => true)
end

def show_CSV
  show_and_save_CSV(:show => true)
end

#2


1  

In your code that currently contains your CSV.foreach(params[:file]), just call two different functions instead - one to save the file, and one to show it:

在当前包含CSV.foreach(params [:file])的代码中,只需调用两个不同的函数 - 一个用于保存文件,另一个用于显示:

def show_CSV f
    CSV.foreach f do |row|
        # show
    end
end

def save_CSV! f
    CSV.foreach f do |row|
        # save
    end
end

def some_calling_function # I'm guessing... in your controller?
    ...
    save_CSV! params[:file]
    show_CSV params[:file]
    ...
end

#1


2  

def show_and_save_CSV(options={})
  CSV.foreach(params[:file]) do |row|
    if options[:show]
      #Showing the parsed CSV
    end
    if options[:save]
      # save
    end
  end
end

Just remember that CSV.foreach loops through the lines of the provided file, so this way you will read the file just once.

请记住,CSV.foreach循环遍历所提供文件的行,因此这样您只需读取一次该文件。

def save_CSV
  show_and_save_CSV(:save => true)
end

def show_CSV
  show_and_save_CSV(:show => true)
end

#2


1  

In your code that currently contains your CSV.foreach(params[:file]), just call two different functions instead - one to save the file, and one to show it:

在当前包含CSV.foreach(params [:file])的代码中,只需调用两个不同的函数 - 一个用于保存文件,另一个用于显示:

def show_CSV f
    CSV.foreach f do |row|
        # show
    end
end

def save_CSV! f
    CSV.foreach f do |row|
        # save
    end
end

def some_calling_function # I'm guessing... in your controller?
    ...
    save_CSV! params[:file]
    show_CSV params[:file]
    ...
end