Method: SimpleData.generate

Defined in:
lib/simple-data.rb

.generate(file, fields, compress = false, tags: nil, sections: nil, &block) ⇒ Object

Generating file



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/simple-data.rb', line 131

def self.generate(file, fields, compress = false,
                  tags: nil, sections: nil, &block)
    # Sanity check
    if compress && !const_defined?(:IOCompressedWrite)
        raise Error, 'compression not supported (add zstd-ruby gem)'
    end

    # Open file
    io = File.open(file, 'w')

    # Magic string
    io.puts "# simple-data:1"

    # Tags
    if tags && !tags.empty?
        io.puts "#"
        tags.each do |name, value|
            io.puts "# @%-8s %s" % [ name, value ]
        end
    end

    # Spec
    io.puts "#"
    io.puts "# --<spec>--"
    maxlen = fields.map {|(_, name)| name.size }.max
    fields.each do |(type, name, desc)|
        if desc
            io.puts "# %-4s : %-*s (%s)" % [ type, maxlen, name, desc ]
        else
            io.puts "# %-4s : %s" % [ type, name ]
        end
    end

    # Custom sections
    if sections && !sections.empty?
        io.puts "#"
        sections.each do |name, value|
            io.puts "# --<#{name}>--"
            value.split(/\r?\n/).each do |line|
                io.puts "# #{line}"
            end
        end
    end

    # Data 
    io.puts "#"
    io.puts "# --<%s>--" % [ compress ? 'data:compressed' : 'data' ]

    # Deal with compression
    io = IOCompressedWrite.new(io) if compress
    
    # Instantiate SimpleData
    sda = self.new(io, fields, :create, tags: tags, sections: sections)
    block ? block.call(sda) : sda
ensure
    sda.close if sda && block
end