Mailinglist Archive: yast-devel (144 mails)

< Previous Next >
Re: [yast-devel] Questions about some YCP Equivalents in ruby
On Tue, 13 Aug 2013 13:30:27 +0200
Thomas Fehr <fehr@xxxxxxx> wrote:

Hi,

While I was just fixing a bug in current head and had to test the
fix anyway I assumed I could easily modify the ruby code needing
to be adapted anyway to a more ruby-like style.

I replaced the common usage of hash access with default parameter by

YCP Code --> Ruby like replacement
part["fsid"]:0 --> (part["fsid"]||0)
part["type"]:`none --> (part["type"]||:none)
substring(part["device"]:"",0,9) --> part["device"][0,9]


Hi Thomas,
at first I would like to mention reason why we have it in Ops, because
in ycp if part is nil, then ycp return default, but ruby will raise
exception.
As others mention problem is false value and also nil value (if
part["fsid"] have value nil, then you get 0 instead. Fetch also solve
it. Or as lslezak mention nice feature with values for missing.

There is one hidden problem, that ycp with `[]:` operator do implicit
conversion of types, which in corner cases can cause different result
for

part["fsid"] = "magic";
y2milestone ("val %1", part["fsid"]:0);
// ycp return nil in this case

But it is usually corner cases and I personally found it quite
stupid behavior.

BTW1 ruby [] takes also range and it is very powerful tool in ruby,
that allows various specification what elements you exactly want[1].

BTW2 for lslezak example I think it can be done better with constant so
it is clear what is default like

PART_DEFAULTS = {
"fsid" => 0,
"type" => :none
}

part = Hash.new { |h,k| PART_DEFAULTS[k] }


NOTE last but not least be aware that in ruby everything is passed as
reference, even constants. So you don't get copy there. If you want
shallow copy then call .dup on specified object ( immutable object
doesn't have it or raise exception ). For deep copy call deep_copy
method, then copy everything except strings ( string are exception,
because it is used a lot in old ycp code and it cause significant
slowdown in ruby ( and old code always use builtins to modify string ),
so maybe we need to introduce new deep_copy for new code, that copy also
strings, but usually you don't need deep copy ).

Josef

[1] http://ruby-doc.org/core-2.0/Array.html#method-i-5B-5D

--
To unsubscribe, e-mail: yast-devel+unsubscribe@xxxxxxxxxxxx
To contact the owner, e-mail: yast-devel+owner@xxxxxxxxxxxx

< Previous Next >
Follow Ups
References