Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow config blocks with identical keys. #14

Open
wrossmann opened this issue May 23, 2018 · 1 comment
Open

Allow config blocks with identical keys. #14

wrossmann opened this issue May 23, 2018 · 1 comment

Comments

@wrossmann
Copy link

wrossmann commented May 23, 2018

Unfortunately my environment is a bit of a disaster which prevents me from using your cookbook directly, but I did lift CollectdConfig::write_elements() for writing collectd configs. However, I have come across some situations where I need multiple config blocks of the same type, eg:

LoadPlugin "foo"
<Plugin "foo">
  <Ignore "bar>
    ...
  </Ignore>
  <Ignore "baz>
    ...
  </Ignore>
</Plugin>

Which doesn't work with the current version of this function, so I've modified it as follows to allow for arrays of hashes:

def write_elements(directives, indent = 0)
  tabs = ("\t" * indent)
  directives.dup.map do |key, value|
    next if value.nil?
    if value.is_a?(Array)
      value.map do |val|
        if val.is_a?(String)
          %(#{tabs}#{key} "#{val}")
        elsif val.is_a?(Hash)
          write_block(key, val, indent)
        else
          %(#{tabs}#{key} #{val})
        end
      end.join("\n")
    elsif value.kind_of?(Hash) # rubocop:disable Style/ClassCheck
      write_block(key, value, indent)
    elsif value.is_a?(String)
      %(#{tabs}#{key} "#{value}")
    else
      %(#{tabs}#{key} #{value})
    end
  end.flatten.join("\n")
end

def write_block(key, value, indent=0)
    tabs = ("\t" * indent)
    id = value.delete('id')
    if id.nil?
      id = ''
    else
      id = " \"#{id}\""
    end
    [%(#{tabs}<#{key}#{id}>),
      write_elements(value, indent.next),
      %(#{tabs}</#{key}>)
    ].join("\n")
end

So now the directive hash below will produce the desired config in the example above.

{
  'LoadPlugin' => 'foo',
  'Plugin' => {
    'id' => 'foo',
    'Ignore' => [
      {
        'id' => 'bar'
        # ...
      },
      {
        'id' => 'baz'
        # ...
      }
    ]
  }
}
@wrossmann
Copy link
Author

Updated write_block to accommodate writing blocks with no id, eg: <Rule>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant