Skip to content

Instantly share code, notes, and snippets.

@theycallmeS
Last active August 29, 2015 14:12
Show Gist options
  • Save theycallmeS/e48fa90c1f599abcd211 to your computer and use it in GitHub Desktop.
Save theycallmeS/e48fa90c1f599abcd211 to your computer and use it in GitHub Desktop.
Proper class_eval in Ruby

Use here_document with class_eval to simplify debugging:

class_eval <<-"end_eval", __FILE__, __LINE__

  def #{block_accessor}(*args, &block)
    unless args.empty? && block.nil?
      args.push block if block_given?
      @#{block_accessor} = [args].flatten
    end

    @#{block_accessor}
  end

end_eval

class_eval (as well as module_eval and some other methods) actually takes blocks or strings for evaluation, so instead of passing a block, we pass everything as a here-document string, and add two additional params for filename and line in that file.

When exception hits the fan, it will be trivial to locate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment