ruby

Allow pasting multiline ruby blocks in Pry when using leading dot notation

We use leading dot notation a lot now e.g.

Foo
  .bar
  .baz

If you copy and paste this into a Pry REPL it throws an error because it doesn't know how to parse it. I thought this was because Pry was parsing differently to IRB but it's actually because Pry has a feature to call system methods by prefixing them with a dot. To be able to copy paste code like this you can simply remove the Pry commands 

Pry.commands.delete /\.(.*)/
6
Joe

Heredoc without interpolation

Sometimes you want to use Ruby's Heredoc without interpolation ('#{....}'). You can do this by adding single dashes around your keyword:
doc = <<-'SONG'
Business men, they drink my wine
#{person} dig my earth
None will level on the line
Nobody offered his word
Hey, hey
SONG

4
Const

Change Ruby version for single command with rbenv

You can switch Ruby version temporarily with rbenv local

But it'd need to be switched back after you're done. Specially for a single command it's kind of pain. In those cases, you can use RBENV_VERSION env variable.

RBENV_VERSION=2.6.3 ruby -v


This might be useful in a shell script or so.

1
Babar

Automagical Intermediate-level Hashtables in Ruby

All intermediate-level hashtables will be created automagically

def autovivifying_hash
   Hash.new {|ht,k| ht[k] = autovivifying_hash}
end


Usage

response_builder = autovivifying_hash
response_builder['payment']['status'] = 'OK'
response_builder # => {"payment"=>{"status"=>"OK"}


Ali

Change VS Code Go to definition to Cmd+Click

Just open your user settings JSON file and use this option:

    "editor.multiCursorModifier": "cmd",


6
Ali

Improve Bundler performance

Level up your bundler performance by running bundler tasks concurrently in jobs:

$ bundle config --global jobs 4


See more options on the bundler website.

1
Const

You can use FactoryBot for non ActiveRecord models

You can use FactoryBot's initialize_with method to initialize an object any way you like which allows you to factorize any of your objects at will

FactoryBot.define do
  factory :citizen_id_image, class: CitizenIdImagePresenter do
    image_url { 'https://placehold.it/200x200' }

    initialize_with { new(image_url: image_url) }
  end
end
build(:citizen_id_image)
#=> 


Introduction


FactoryBot is a popular testing tool for Ruby on Rails applications that allows developers to define and create test fixtures on the fly. It provides a flexible and efficient way to create test data, making it easier to write and maintain tests. In this article, we will explore how to use FactoryBot effectively in Rails testing.

Setting up FactoryBot


To set up FactoryBot in your Rails application, you need to add the factory_bot gem to your Gemfile and run the bundle install command. You can then configure FactoryBot by creating a factory_bot.rb file in the config/initializers directory. In this file, you can define the factory_bot configuration, such as the factory paths and the default strategy.

Defining Models and Factories


In FactoryBot, a factory is a blueprint for creating an object. You can define a factory for a model by creating a file in the factories directory. For example, if you have a User model, you can create a user.rb file in the factories directory to define the user factory. In this file, you can define the attributes and associations for the user factory.

Factory Options and Attributes


FactoryBot provides several options and attributes that you can use to customize your factories. For example, you can use the class attribute to specify the class of the object being created. You can also use the attributes option to define the attributes for the factory. Additionally, you can use the association option to define associations between factories.

Conclusion


In conclusion, FactoryBot is a powerful tool for creating test fixtures in Rails applications. By defining factories for your models, you can create test data quickly and efficiently. With its flexible configuration options and customizable attributes, FactoryBot makes it easy to write and maintain tests. By following the best practices outlined in this article, you can get the most out of FactoryBot and improve the quality of your tests.
6
Joe

optional relation + RSpec w/shoulda-matchers

User 1 - 0..1 Laptop

  • Model ```ruby a/m/user.rb has_one :laptop

a/m/laptop.rb belongs_to :user, optional: true ```

  • spec ruby s/m/laptop_spec.rb it { should belong_to(:user).optional }
1.07 Thousand
Alyson

Remove ruby 2.6 bundled bundler

Generating a rails 6 app with ruby 2.6+ when you have bundler v2 installed creates unusable binstubs. If you are seeing this error You must use Bundler 2 or greater with this lockfile. you can remove the bundler that comes bundled with ruby 2.6 and rely on the manually installed v2 bundler.

If you are using rbenv you can use this command (adjust for your ruby version e.g. 2.6.{0, 1} etc), other installation systems will use different locations

rm -rf ~/.rbenv/versions/2.6.1/lib/ruby/2.6.0/bundler*


1.07 Thousand
Joe

Suppress rspec warnings

$ RUBYOPT=W0 ./bin/rspec spec/
...

$ RUBYOPT=W0 bundle exec rspec spec/
...

$ RUBYOPT=W0 rspec
...

$ RUBYOPT=W0 ...
...


RSpec warnings can clutter your test output and make logs harder to read, especially in large Rails projects. Here’s how to suppress them effectively while maintaining a clean workflow.

Suppress Warnings Globally


You can disable warnings for your entire test suite by adding the following to spec_helper.rb or rails_helper.rb:

$VERBOSE = nil
Use Case: Ideal for quickly silencing all warnings, but it may hide important information across your app and dependencies.

Suppress Specific Warnings


Wrap warning-generating code in a suppression block:

def suppress_warnings 
original_verbose = $VERBOSE 
$VERBOSE = nil 
yield 
ensure 
$VERBOSE = original_verbose 
end 

suppress_warnings do 
require 'some_gem_with_warnings' 
end

Use Case: Useful for isolating warnings to specific dependencies or blocks of code.

Suppress RSpec Warnings


RSpec provides built-in configuration for managing its own warnings. Add this to your spec_helper.rb:

RSpec.configure do |config| 
config.warnings = false 
end

Use Case: Suppresses RSpec-specific warnings while keeping Ruby and dependency warnings visible.

Redirect Deprecation Warnings


For deprecation warnings, redirect them to a log file for review:

RSpec.configure do |config| 
config.deprecation_stream = File.open('log/rspec_deprecations.log', 'w') 
end

Use Case: Keeps test output clean while preserving visibility into deprecations.

Environment-Specific Suppression


Suppress warnings only in specific environments, such as CI:

$VERBOSE = nil if ENV['SUPPRESS_WARNINGS'] == 'true'
Use Case: Allows warnings during local development but hides them in CI for cleaner logs.

By tailoring these approaches to your needs, you can keep your test outputs clean and actionable, improving productivity in development and CI workflows.
1.07 Thousand
Ali

Run rubocop against your current branch

$ git diff develop feature/one-signal --diff-filter=M --name-only -- *.rb | egrep -v 'db|config|spec' | xargs rubocop


2
Ali

Run rubocop before commit

Introduction


Git hooks are super powerful for automating tasks and enforcing coding standards in a Git repository. One common use case for Git hooks is to run automated tests and code analysis tools before allowing a commit to proceed. In this article we’ll cover pre-commit hooks, how to skip them and how to set up a pre-commit hook to run Rubocop, a Ruby code analysis tool.

What is Rubocop?


Rubocop is a static code analysis tool for Ruby that checks code for style and security issues. It’s a popular tool among Ruby developers to ensure their code follows the Ruby style guide and best practices. Rubocop can be run manually but integrating it with a pre-commit hook ensures code is checked automatically before each commit.

Copy this into .git/hooks/pre-commit (remove .sample)

#!/usr/bin/env ruby

require 'english'
require 'rubocop'

ADDED_OR_MODIFIED = /A|AM|^M/.freeze

changed_files = `git status --porcelain`.split(/\n/).
    select { |file_name_with_status|
      file_name_with_status =~ ADDED_OR_MODIFIED
    }.
    map { |file_name_with_status|
      file_name_with_status.split(' ')[1]
    }.
    select { |file_name|
      File.extname(file_name) == '.rb'
    }.join(' ')

system("rubocop #{changed_files}") unless changed_files.empty?

exit $CHILD_STATUS.exitstatus



Make it executable 

$ chmod +x .git/hooks/pre-commit



You're good to go, from now it'd run rubocop against your changes and prevents from commiting unless you fix the offences.

How to skip pre-commit? just pass -n to git commit

$ git commit -n -m "[hotfix] blah blah"


What is a Pre-Commit Hook?


A pre-commit hook is a client-side Git hook that runs before a commit is created. It’s a script that can do various things like run automated tests, check code style or enforce coding standards. If the pre-commit hook fails the commit is aborted and you have to fix the issues before committing again.

Why Run Rubocop Before Commit


Running Rubocop before commit has several advantages:

  • Code quality: Rubocop checks code for style and security issues so the codebase is consistent and secure.
  • Time saver: By running Rubocop automatically before commit you can catch issues early and avoid wasting time debugging later.
  • Collaboration: By enforcing coding standards pre-commit hooks promote collaboration and consistency among team members.

How to set up a pre-commit hook

  1. Install Rubocop and the pre-commit hook tool of your choice (e.g., Husky or Pre-commit).
  2. Create a new file in the .git/hooks directory called pre-commit.
  3. Add the Rubocop command to the pre-commit file, e.g., rubocop -a.
  4. Make the pre-commit file executable by running chmod +x .git/hooks/pre-commit.
  5. Test the pre-commit hook by running git commit -m “Test commit”

Note: If you want to skip the pre-commit hook temporarily you can use the –no-verify option with the git commit command, e.g., git commit -m “Test commit” –no-verify.
1.07 Thousand
Ali