Skip to content

Commit

Permalink
include autoconvert into Ops.get
Browse files Browse the repository at this point in the history
  • Loading branch information
jreidinger committed Jul 11, 2013
1 parent 2d623b6 commit c0243b9
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 6 deletions.
4 changes: 2 additions & 2 deletions src/ruby/yast/convert.rb
Expand Up @@ -17,8 +17,8 @@ def self.to_#{type}(object)
end

def self.convert(object, options)
from = options[:from]
to = options[:to]
from = options[:from].dup
to = options[:to].dup

#ignore whitespaces and specialization in types
to.gsub!(/<.*>/, "")
Expand Down
20 changes: 20 additions & 0 deletions src/ruby/yast/ops.rb
@@ -1,6 +1,7 @@
require "yast/yast"
require "yast/path"
require "yast/logger"
require "yast/convert"

#predefine term to avoid circular dependency
class Yast::Term;end
Expand Down Expand Up @@ -67,6 +68,25 @@ def self.get (object, indexes, default=nil)
return block_given? ? yield : default
end
end

#included automatic conversion based on type of default
unless default.nil? #nil is any, but false is boolean
target_type = ""
TYPES_MAP.each_pair do |k,v|
values = v.is_a?(::Array) ? v : [v]
if values.any? { |val| val == default.class }
target_type = k
break
end
end

if target_type.empty?
Yast.y2internal "wrong type '#{default.class}' for index"
else
res = Convert.convert(res, :from => "any", :to => target_type)
end
end

return Yast.deep_copy(res)
end

Expand Down
10 changes: 6 additions & 4 deletions tests/ruby/ops_test.rb
Expand Up @@ -164,7 +164,7 @@ def test_comparison_mixture

def test_index_map
map = { "a" => { "b" => "c" }}
assert_equal({ "b" => "c"}, Yast::Ops.index(map,"a","n"))
assert_equal({ "b" => "c"}, Yast::Ops.index(map,"a",{}))
assert_equal "c", Yast::Ops.index(map,["a","b"],"n")
assert_equal "n", Yast::Ops.index(map,["a","c"],"n")
assert_equal "n", Yast::Ops.index(map,["c","b"],"n")
Expand All @@ -173,7 +173,7 @@ def test_index_map

def test_index_list
list = [["a","b"]]
assert_equal(["a","b"], Yast::Ops.index(list,0,"n"))
assert_equal(["a","b"], Yast::Ops.index(list,0,[]))
assert_equal "b", Yast::Ops.index(list,[0,1],"n")
assert_equal "n", Yast::Ops.index(list,[0,2],"n")
assert_equal "n", Yast::Ops.index(list,[1,1],"n")
Expand All @@ -196,8 +196,10 @@ def test_index_mixture

def test_index_corner_cases
list = ["a"]
assert_equal "n", Yast::Ops.index(list,["a"],"n")
assert_equal "n", Yast::Ops.index(list,[0,0],"n")
assert_equal "n", Yast::Ops.index(list,["a"],"n")
assert_equal "n", Yast::Ops.index(list,[0,0],"n")
assert_equal 1, Yast::Ops.index([1.0],0,0)
assert_equal nil, Yast::Ops.index([1.0],0,"")
end

def test_assign
Expand Down

0 comments on commit c0243b9

Please sign in to comment.