Skip to content

Commit

Permalink
Implement Ops.get_* shortcut methods
Browse files Browse the repository at this point in the history
In code geenreated by Y2R, we often have pieces like this:

  Convert.to_string(Ops.get(l, 0, "foo"))

This code is typically emitted because the original collection is
untyped.

Because this pattern appears over and over, we decided to simplify it to
something like this:

  Ops.get_string(l, 0, "foo"))

That is, introduce and use shortcut methods that would combine getting
an item from a collection with type conversion.

This commit adds needed shortcut methods to Ruby bindings. It will be
followed by a commit in Y2R that will generate code which will use them.
  • Loading branch information
dmajda committed Jul 17, 2013
1 parent 102d90a commit b4eddc1
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
3 changes: 1 addition & 2 deletions src/ruby/yast/convert.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ module Yast
module Convert

#generate shortcuts
[ "boolean", "string", "symbol", "integer", "float", "list", "map",
"term", "path", "locale" ].each do |type|
Ops::SHORTCUT_TYPES.each do |type|
eval <<END
def self.to_#{type}(object)
convert object, :from => "any", :to => "#{type}"
Expand Down
22 changes: 22 additions & 0 deletions src/ruby/yast/ops.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,28 @@ module Ops
'byteblock' => Yast::Byteblock
}

# Types for which we generate shortcut methods, e.g. Ops.get_string or
# Convert.to_string.
SHORTCUT_TYPES = [
"boolean",
"string",
"symbol",
"integer",
"float",
"list",
"map",
"term",
"path",
"locale"
]

Ops::SHORTCUT_TYPES.each do |type|
eval <<END
def self.get_#{type}(*args, &block)
Yast::Convert.to_#{type} get(*args, &block)
end
END
end

def self.index (*args, &block)
get *args, &block
Expand Down
7 changes: 7 additions & 0 deletions tests/ruby/ops_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
require "test_helper"

require "yast/ops"
require "yast/convert"
require "yast/path"
require "yast/term"

Expand Down Expand Up @@ -200,6 +201,12 @@ def test_index_corner_cases
assert_equal "n", Yast::Ops.index(list,[0,0],"n")
end

def test_get_shortcuts
list = ["a","b"]
assert_equal("a", Yast::Ops.get_string(list,0,"n"))
assert_equal(nil, Yast::Ops.get_integer(list,0,"n"))
end

def test_assign
l = nil
Yast::Ops.assign(l,[1,2],5)
Expand Down

0 comments on commit b4eddc1

Please sign in to comment.