How to trim a string and fill remaining space in Ruby

So I needed a way to take a string, and depending on its size, shorten it and fill the remaining space with some arbitrary sequence of characters. Ljust would work, except for the fact that it will fill a string up to a given length, but I only needed to do this when over a certain size. Here is an example:

str = "Somereallylongstring"
if str.length > 10
  puts str[0..7] + "…"
else
  puts str
end
# => "Somerea..."

This is the basic idea of what I wanted to do. I decide to make it cleaner and override the String class like so:

class String
  def lfill(len = self.length, fill = ".")
    tmp = self[0..(len – 3)] + "..." if self.length – 3 > len
    return tmp || self
  end
end

nstr = "Somereallylongstring"
puts str.lfill(10)
#=> "Somerea..."

 

How to merge strings just like ActiveRecord conditions do

While you can achieve the same functionality using sprintf, this may provide a cleaner approach and one that you are more familiar with. This will allow you to build a string the same way you can use ActiveRecord and the :conditions option.

Basically how this works is by overriding the Array class and adding a method to merge the string and values together into unified string! Enough talk, lets see some code:

class Array
  def merge
    statement, *values = self
    expected = statement.count("?")
    provided = values.size
    unless expected.eql?(provided)
      raise "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}"
    end
    bound = values.dup
    statement.gsub("?") { bound.shift }
  end
end

As you can see, if you do not provide the right number of values for the statement, it will raise and error. Here is how you would use it:

puts ["Hello ?, how are you", "John"].merge
#=> Hello John, how are you

Likewise, you can use variables to hold values:

message = "Hello ?, how are you"
name = "John"
puts [message, name].merge
#=> Hello John, how are you

This will also work with multiple values:

puts ["Hello ?, ? and ?, how are you", "John", "Joe", "Jim"].merge
#=> Hello John, Joe, and Jim, how are you

The only downside to this currently is that you cannot use a ? in the string you are merging, as it will think its a binding character.

Moving files in Rails using String

Since ruby allow for really easy overriding of objects and classes, I decided to make it easier and cleaner to move my files. Here is how you currently do it:

FileUtils.move("/path/to/file", "/path/to/new/file")

I know this isn’t a huge deal, but I would like to clean it up a little bit. I used an initializer (RAILS_ROOT/config/initializers/core_extensions.rb) to override the String class as such:

class String
  def move(to = nil)
    if to && File.exist?(self)
      FileUtils.move(self, to)
    end
  end
end

This allows me to do the following to move files:

"/path/to/file".move("/path/to/new/file")

I though it was pretty cool!