Skip to content

Commit

Permalink
Change to add ability to specify generated content key value separato…
Browse files Browse the repository at this point in the history
…r in ref issue #4
  • Loading branch information
piotrmurach committed Sep 29, 2018
1 parent 9def07b commit 9916d07
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 18 deletions.
37 changes: 19 additions & 18 deletions lib/tty/config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,43 +38,44 @@ def self.normalize_hash(hash, method = :to_sym)
# the file content
#
# @api public
def self.generate(data)
content = []
values = {}
def self.generate(data, separator: '=')
content = []
values = {}
sections = {}

data.keys.sort.each do |key|
val = data[key]
if val.kind_of?(NilClass)
if val.is_a?(NilClass)
next
elsif val.kind_of?(Hash) || (val.kind_of?(Array) && val.first.kind_of?(Hash))
elsif val.is_a?(Hash) ||
(val.is_a?(Array) && val.first.is_a?(Hash))
sections[key] = val
elsif val.kind_of?(Array)
values[key] = val.join(",")
elsif val.is_a?(Array)
values[key] = val.join(',')
else
values[key] = val
end
end

# values
values.each do |key, val|
content << "#{key} = #{val}"
content << "#{key} #{separator} #{val}"
end
content << "" unless values.empty?

# sections
sections.each do |section, object|
unless object.empty? # only add section if values present
content << "[#{section}]"
if object.kind_of?(Array)
object = object.reduce({}, :merge!)
end
object.each { |key, val|
val = val.join(',') if val.kind_of?(Array)
content << "#{key} = #{val}" if val
}
content << ""
next if object.empty? # only add section if values present

content << "[#{section}]"
if object.is_a?(Array)
object = object.reduce({}, :merge!)
end
object.each { |key, val|
val = val.join(',') if val.is_a?(Array)
content << "#{key} #{separator} #{val}" if val
}
content << ""
end
content.join("\n")
end
Expand Down
30 changes: 30 additions & 0 deletions spec/unit/generate_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,34 @@
array = 1,2,3
EOS
end

it "generate config content with custom separator" do
conf = {
'str' => 'hello',
'array' => [1,2,3],
'deep_array' => [
{foo: 1},
{bar: 2}
],
'section' => {
'value' => 1,
'array' => [1,2,3]
}
}

content = TTY::Config.generate(conf, separator: ':')

expect(content).to eq <<-EOS
array : 1,2,3
str : hello
[deep_array]
foo : 1
bar : 2
[section]
value : 1
array : 1,2,3
EOS
end
end

0 comments on commit 9916d07

Please sign in to comment.