[chef] Re: Re: Re: Re: Re: Re: Re: Re: Re: attributes inheritance


Chronological Thread 
  • From: Daniel DeLeo < >
  • To:
  • Subject: [chef] Re: Re: Re: Re: Re: Re: Re: Re: Re: attributes inheritance
  • Date: Wed, 24 Jul 2013 08:49:50 -0700


On Wednesday, July 24, 2013 at 5:56 AM, Cassiano Leal wrote:

Nice article. I’m a Ruby dev, so it didn’t really present me with anything new, but it’s got great information summarised in a nice way.


I use ||= all the time when programming in Ruby. It’s a great shortcut for memoisation and some logical operations.


The article is a great reminder that you need to understand how it works before using it everywhere, though. :)

Generally ||= is fine (though not thread safe, if you're writing a threaded application--not a big deal for chef code though). The problem with using it with node attributes is that it's incompatible with the "auto-vivify" feature. Auto-vivify is the thing that lets you write node.default[:foo][:bar][:baz] = "qux" when none of the intermediate hashes exist. Behind the scenes, chef is creating a new mash each time you access a key that does not exist. This is different from regular ruby code where the default behavior when accessing a key that doesn't exist is to return nil[1] which is a "falsey" value. For this reason, default_unless and other _unless methods are provided to give you ||= type behavior.

-- 
Daniel DeLeo


1. In regular ruby, you can change the default behavior of hashes when accessing missing keys by passing a block to Hash.new. For example, if you want to inflict code rage on someone, you could stick this in their code base:

chef > h = Hash.new {|h,k| true }
 => {} 
chef > h[:foo]
 => true 
chef > h[:foo] ||= "bar"
 => true 
chef > h
 => {} 





Archive powered by MHonArc 2.6.16.

§