我是一名PHP开发者,正在努力提高自己的Ruby技能。我现在正在尝试开发一个源代码审计工具,用于扫描多种web编程语言的webapp文件中可能存在的危险函数。当匹配项被找到时,脚本会将相关信息保存在一个poi(point-of-interest)类中,以便稍后显示。
该类的一个示例实例如下(采用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,但是没有成功:
我已经尝试将此思想从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|
作为额外的参考,这是将
@points_of_interest
转换为YAML格式后的样子(以下是代码片段):- !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