Jai*_*yer 16
Rails的脚手架生成器在添加路由时config/routes.rb 执行此操作它通过调用一个非常简单的方法来实现:
def gsub_file(relative_destination, regexp, *args, &block)
path = destination_path(relative_destination)
content = File.read(path).gsub(regexp, *args, &block)
File.open(path, 'wb') { |file| file.write(content) }
end
Run Code Online (Sandbox Code Playgroud)
它正在做的是将路径/文件作为第一个参数,然后是正则表达式模式,gsub参数和块.这是一种受保护的方法,您必须重新创建才能使用.我不确定destination_path你是否有权访问,所以你可能想要传递确切的路径并跳过任何转换.
要使用gsub_file,假设您要为用户模型添加标签.这是你如何做到的:
line = "class User < ActiveRecord::Base"
gsub_file 'app/models/user.rb', /(#{Regexp.escape(line)})/mi do |match|
"#{match}\n has_many :tags\n"
end
Run Code Online (Sandbox Code Playgroud)
您正在文件中找到特定的行,开启类,并has_many在下方添加您的行.
请注意,因为这是添加内容最脆弱的方式,这就是为什么路由是使用它的唯一地方之一.上面的例子通常用混合处理.
| 归档时间: |
|
| 查看次数: |
2723 次 |
| 最近记录: |