Stop spec_helper from being loaded multiple times

If you got a big project, chances are spec_helper is required through different ways, File.expand_path / File.join() / … which results in it being loaded several times!

Try it:

#spec_helper.rb
print "YEP!"

rake spec -> “YEP!YEP!YEP!YEP!YEP!YEP!YEP!YEP!……”

So how to prevent it ?

Unify!
Unify it to ‘spec_helper’ for rspec or ‘./spec/spec_helper’ for minitest, which can be copied without modification (like adding ‘../../’) and prevents duplicate spec_helper calls

#unify_spec_helper.rb
files = Dir["spec/**/*_spec.rb"].reject{|file|File.directory?(file)}
files.each do |file|
  lines = File.readlines(file)
  lines = lines.map do |line|
    if line =~ /require.*spec_helper/
      "require 'spec_helper'\n"
    else
      line
    end
  end
  File.open(file,'w'){|f| f.write lines.join('') }
end

Run: ruby unify_spec_helper.rb

ActiveRecord.find_each_with_order = find_each with order…

I just hate things that fail silently, just like User.order_by(:created_at).find_each

Which will simply ignore the order option….

So here comes the alternative…

class ActiveRecord::Base
  # normal find_each does not use given order but uses id asc
  def self.find_each_with_order(options={})
    raise "offset is not yet supported" if options[:offset]

    page = 1
    limit = options[:limit] || 1000

    loop do
      offset = (page-1) * limit
      batch = find(:all, options.merge(:limit => limit, :offset => offset))
      page += 1

      batch.each{|x| yield x }

      break if batch.size < limit
    end
  end
end

(the 😮 is : and o)

Unobstrusive word_wrap aka split_after for Ruby / Rails

Evil users often write something like “SomeThingNewAndGreat,use,it aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa” just to annoy us developers who try to get their content into a 50x100px div (at least I suspect it…).

Usage
(Use it after truncating, since it adds additional characters)

#!invisible char between 6 and 7!
"12345 12345678".split_after(3) == "12345 123456​78"
"12345 12345678".split_after(6, :with=>'<br />') == "12345 123456<br />78"

Code

  # splits to long words after max chars with invisible "zero-length-space"
  # UTF8 char that should display in all browsers
  # http://www.fileformat.info/info/unicode/char/200b/index.htm
  def split_after(max, options={})
    zero_length_space = '​' #aka ​
    options[:with] ||= zero_length_space

    split(/ /).map do |part|
      part = part.mb_chars
      if part.length > max
        part[0...max] + options[:with] + part[max..-1].to_s.split_after(max)
      else
        part
      end
    end * ' '
  end