There are other ways you could write this but I'm not sure if you'd find any of them cleaner. One option is plain old sprintf
. For example:
# assemble file name
fname = sprintf("%s/%s-%i-%s-%ix%i.png", directory, prefix, timestamp,
commit, size[:width], size[:height])
You could shorten it a little by giving size
its own to_s
method:
class << size; def to_s; "#{self[:width]}x#{self[:height]}" end end
fname = sprintf("%s/%s-%i-%s-%s.png", directory, prefix, timestamp,
commit, size)
...and perhaps create other convenience methods along the same lines. But still, very small gains.
Another option would be to make your own super-small template engine, something like this:
def tiny_subst template, bndg
param_exp = /:(\w+)[^\w:]+/i
tmpl_params = template.scan(param_exp).flatten
proc {
out_str = template.clone
tmpl_params.reduce(out_str) do |str, p|
puts p
str.gsub ":#{p}", eval(p, bndg).to_s unless p.empty?
end
}
end
tmpl = ':directory/:prefix-:timestamp-:commit-:size.png'
subber = tiny_subst(tmpl, binding)
directory = 'screenies'
prefix = 'screenshot'
timestamp = Time.now.to_i
commit = '0b5c7967887481deb17bcd9039cd3fe0ac4540d4'
size = '640x960'
subber.yield # => screenies/screenshot-1316535022-0b5c7967887481deb17bcd9039cd3fe0ac4540d4-640x960.png
commit = 'foobarbazquux'
size = '9000x9000'
subber.yield # => screenies/screenshot-1316535022-foobarbazquux-9000x9000.png
So, that's kinda nice, but is it really worth it? Not for me, but I guess if you really hate "#{this}
" it might be.