Ruby remove ternary conditions

Somethimes you want to do something conditionally depending on a boolean.
(I don't like the double question mark in ternary-if)

For example:

# add a class to an element
tag.div(class: selected? ? "sample" : nil)

# executing code conditionaly:
if selected? 
    #.. code

This code could be rewritten like this:

# add a class to an element
tag.div(class: selected? { "sample" })

# executing code conditionaly: (this could be done, no per se an improvement)
selected? do
    #.. code

To use the construct above, give the boolean operation the following content.

  • if a block is given and the condition is true it invokes the block else it returns nil
  • if no block is given, the boolean is returned
def selected?
    return selected? ? yield : nil if block_given?


Ruby check if gem is loadable

Sometimes you want to only execute a given piece of code if a specific gem has is available. Testing if a constant is defined doesn't aslways work when using autoloading.


Derailed benchmark not running on production environment

We're running a large rails application, with a lot of request.
Since our upgrade to FreeBSD 13 the live environment is leaking memory in our ruby on rails app.
(FreeBSD 12 version of the jail didn't leak)

This application uses an NFS mount to store (a lot) of client specific files.

Running derailed_benchmark live didn't work. (Pressing ctrl+t, I noticed there were a lof of NFS locks)

In the file

it adds '.' to the loadpath. Which causes the production environment to complete iterate over all directories. Which 'hangs', because we have a very big active-strorage directory.

Workaround is to remove the '.' file

#    %W{ . lib test config }.each do |file|
    %W{ lib test config }.each do |file|
      $LOAD_PATH << File.expand_path(file)

Ruby rbtrace ArgumentError: command is too long

(This code blow requires you to include rbtrace in your gems)

To make a stack dump of your running rubyprocess, you could use somthing like this:

bundle exec rbtrace -p $my_pid -e '{GC.start;require "objspace";"/tmp/ruby-heap.dump", "w"); ObjectSpace.dump_all(output: io); io.close}'

Unfortunately on FreeBSD / Mac OS X this results in (ArgumentError: command is too long)

A workaround for this, is to simply put the code in ruby file, and just load it. For example:
/tmp/rbcode.rb. With the following content{GC.start;require "objspace";"/tmp/ruby-heap.dump", "w"); ObjectSpace.dump_all(output: io); io.close}

Next you can use rbtrace lik this:

bundle exec rbtrace -p $my_pid -e 'load("/tmp/rbcode.rb")'