我需要比较HTTP URL中的查询。这是一个典型的查询:
a1 = "name=blabla&id=123456"
查询可能包含变量,例如:
a2 = "name=blabla&id={CustomID}"
blur_compare(a1, a2)
应为true
。以下是其他情况:
a3 = "height=170&sex=male"
a4 = "name=blabla"
a5 = "name=blabla&id=654321"
a6 = "id={CustomeID}&name={CustomeName}"
blur_compare(a3, a2) #=> false, params doesn't match.
blur_compare(a4, a2) #=> false, param's number doesn't match.
blur_compare(a5, a1) #=> false, the id doesn't match.
blur_compare(a6, a2) #=> true. order doesn't matter.
我正在考虑将字符串转换为哈希,例如
{"name" => "blabla", "id" => "123456"}
然后进行比较。但是我的代码很乱,又长又丑。很多if
- else
条件。我想知道是否有更好的方法可以做到。
对不起,这是代码。分享它有点害羞,特别是当它写得不好时。但我正在学习:)。
path_query.rb
class PathQuery
def self.is_var?(str)
regex = /^{.*}$/
str =~ regex ? true : false
end
def self.blur_match_query?(query1, query2)
# deal with the condition when query1 or query2 maybe nil
if query1 == nil && query2 == nil
return true
elsif query1 == nil || query2 == nil
return false
else
end
res = true
# return false directly if number of keys is not equal
if query1.keys.size == query2.keys.size
query1.each{|k,v|
# when the value of same key is diff, then need to found out if one of them is variable.
if v != query2[k]
if not (PathQuery.is_var?(v) || PathQuery.is_var?(query2[k]))
res = false
break
end
end
}
else
res = false
end
res
end
end
test_path_query.rb
class TestPathQuery < Minitest::Test
def test_blur_match_query?()
a1 = {"name" => "blabla", "id" => "123456"}
a2 = {"name" => "blabla", "id" => "{CustomID}"}
a3 = {"height" => "170", "sex" => "male"}
a4 = {"name" => "blabla"}
a5 = {"name" => "blabla", "id" => "654321"}
a6 = {"id" => "{CustomeID}", "name" => "{CustomeName}"}
assert_equal true, PathQuery.blur_match_query?(a1, a2)
assert_equal false, PathQuery.blur_match_query?(a1, a3)
assert_equal false, PathQuery.blur_match_query?(a4, a2)
assert_equal false, PathQuery.blur_match_query?(a5, a1)
assert_equal true, PathQuery.blur_match_query?(a6, a2)
assert_equal true, PathQuery.blur_match_query?(nil, nil)
assert_equal false, PathQuery.blur_match_query?(nil, a2)
end
end
答案 0 :(得分:0)
试试这个
use App\Option;
PageController extends Controller{
public function __construct(Option $option){
$this->option = $option;
}
public function about(){
$options = $this->option->list('id','value');
return view('about', $options);
}
}