Ruby: Tips & Tricks
General
Rapidly Compute the CIDR Range
Use IPAddr#to_range:
irb(main):001> require "ipaddr"
=> true
irb(main):002> IPAddr.new("192.168.128.0/19").to_range
=> #<IPAddr: IPv4:192.168.128.0/255.255.255.255>..#<IPAddr: IPv4:192.168.159.255/255.255.255.255>
To check whether an IP address belongs to the range:
irb(main):003> IPAddr.new("10.101.64.0/18") === "127.0.0.2"
=> false
RSpec
Debugging a Failing Expectation
When a spec is failing, the displayed error cause is truncated. Sometimes, it makes it difficult to understand what happened.
To solve this, RSpec provides a way to control the length of the output:
RSpec::Support::ObjectFormatter.default_instance.max_formatted_output_length = 2000
Setting this to nil will not limit the output.
Silencing write to standard output
Some code may write to the standard output using the Kernel#puts or
Kernel#print which pollute the output when running rspec. To
silence the noisy code, we can add in a before block:
before { allow($stdout).to receive(:puts) }
Mocking the production environment
In Rails, we sometimes need to validate a specific behaviour in production environment. To simulate that, we can do something like:
before do allow(Rails) .to receive(:env) .and_return(ActiveSupport::StringInquirer.new('production')) end