我是一名 PHP 开发人员,正在尝试精通 Ruby。我现在正在努力的一个项目是一个源代码审计工具,它可以扫描 webapp 文件以查找几种 web 编程语言中的潜在危险功能。找到匹配项后,脚本会将相关信息保存在poi
(兴趣点)类中,以便稍后显示。
该类的示例实例如下所示(以 YAML 建模):
poi:
file_type: "php"
file: "the-scanned-file.php"
line_number: 100
match: "eval()"
snippet: "echo eval()"
在展出时,我想像这样组织这些兴趣点:
- file_type
-- file
--- match (the searched payload)
因此,在演示之前,我试图将一个平面poi
对象数组构造成一个哈希镜像上面的结构。这将允许我简单地遍历散列中的项目以生成所需的屏幕组织。(或者至少,这是计划。)
现在,对于我的问题:我如何在 Ruby 中做到这一点?
在 PHP 中,我可以很容易地做这样的事情:
<?php
$sorted_pois = array();
foreach($points_of_interest as $point){
$sorted_pois[$point->file_type][$point->file][$point->match][] = $point;
}
?>
我试过像这样将这种想法从 PHP 翻译成 Ruby,但无济于事:
sorted_pois = {}
@points_of_interest.each_with_index do |point, index|
sorted_pois[point.file_type.to_sym][point.file.to_sym][point.match.to_sym].push point
end
我在这上面花了几个小时,此时我有点把头撞在墙上,所以大概我离基地很远。在 Ruby 中处理这个问题的正确方法是什么?
更新:
作为参考,这是我定义的精确方法:
# sort the points of interest into a structured hash
def sort
sorted_pois = {}
@points_of_interest.each_with_index do |point, index|
sorted_pois[point.file_type.to_sym][point.file.to_sym][point.match.to_sym].push point
end
end
这是我在运行代码时收到的错误:
./lib/models/vulnscanner.rb:63:in `sort': undefined method `[]' for nil:NilClass (NoMethodError)
from /usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `each_with_index'
from ./lib/models/vulnscanner.rb:62:in `each'
from ./lib/models/vulnscanner.rb:62:in `each_with_index'
from ./lib/models/vulnscanner.rb:62:in `sort'
from ./webapp-vulnscan:69
第 62 行(正如您可能推断的那样)尤其是这一行:
@points_of_interest.each_with_index do |point, index|
作为附加参考,以下是转换为 YAML 时的(一段)@points_of_interest
外观:
- !ruby/object:PoI
file: models/couponkimoffer.php
file_type: php
group: :dangerous_functions
line_number: "472"
match: `
snippet: ORDER BY `created_at` DESC
- !ruby/object:PoI
file: models/couponkimoffer.php
file_type: php
group: :dangerous_functions
line_number: "818"
match: `
snippet: WHERE `company_slug` = '$company_slug'
- !ruby/object:PoI
file: models/couponkimoffer.php
file_type: php
group: :dangerous_functions
line_number: "819"
match: `
snippet: ORDER BY `created_at` DESC