如何将文件从gets.chomp传递到文件

时间:2017-08-13 04:18:20

标签: ruby

我想将resources :#{get}推到resources :posts的底部。

get = gets.chomp
@file = File.open('config/routes.rb','r+')
myString = "
  resources :#{get}s
"

Rails.application.routes.draw do
  resources :users do
    resources :posts
  end
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

结果是:

Rails.application.routes.draw do
  resources :users do
    resources :posts
    resources :categories
  end
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

如何将数据从用户输入传递到文件?

1 个答案:

答案 0 :(得分:2)

假设路线文件中只有一个resources :posts,可以这样做一个简单的例子:

require 'active_support/core_ext/string/inflections' # for `pluralize`

get = gets.chomp
lines = File.read("config/routes.rb").split(/\n/)

# find the line of the file we want to insert after. This assumes
# there will only be a single `resources :posts` in your routes.
index = lines.index { |line| line.strip == 'resources :posts' }
# duplicate the existing line and replace 'posts' with the pluralized form
# of whatever the user input to gets, we do it this way to keep indentation
new_line = lines[index].gsub(/posts/, get.pluralize)

# insert the new line on the line after the `resources :posts` and then write
# the entire thing back out to 'config/routes.rb'
lines.insert(index + 1, new_line)
File.open("config/routes.rb", "w") { |f| f.write(lines.join("\n")) }

根据您尝试做的事情,您可能会发现查看Rails Generators很有用。

<强>前

Rails.application.routes.draw do
  resources :users do
    resources :posts
  end
end

<强>执行

$ echo category | ruby example.rb

<强>后

Rails.application.routes.draw do
  resources :users do
    resources :posts
    resources :categories
  end
end