Revert a file to a specific version in git

To revert a commit in git you can use the git revert command, this undoes all the changes of the given commit with a new commit. But what if you only want to revert one specific file to a specific revision?

First you need to identify the revision that you are after by using the git log command, you can see the history of a specific file by appending it to the command:

$ git log README.txt
commit 20f4b96db867e471b16b1392af0ffe05f2c5976e (HEAD -> feature-c)
Author: Mark Cornelissen <mark@boxture.com>
Date:   Thu Oct 7 20:03:20 2021 +0200

    Adding even more text, and FILE2

commit 30d3c934363f7effe51ac528cd1ce16dbab2bf57
Author: Mark Cornelissen <mark@boxture.com>
Date:   Thu Oct 7 20:02:28 2021 +0200

    Adding some more text and FILE1

commit d2bcd858aadf352f0fb33fe33249a972e08e3301 (origin/trunk, origin/HEAD, trunk)
Author: Mark Cornelissen <mark@boxture.com>
Date:   Sat Nov 7 08:50:17 2020 +0100

    Initial commit

Then use the git checkout command to get the version that you want to restore:

$ git checkout 30d3c934363f7effe51ac528cd1ce16dbab2bf57 -- README.txt
$ git status
On branch feature-c
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        modified:   README.txt

The selected revision is now staged for commit, you can now either make further changes to it or commit it directly.

If you want to try the commands from this article you can get a copy of the repository I used from GitHub (and checkout branch feature-c though).

Stashing part of your changes with git

Do you ever run into that situation while coding where you need to temporarily undo some of your uncommitted changes? I sure do.

If you are a git user you have likely used git’s stash feature, this allows you to park changes that you have made rather than committing them. If you didn’t know already: you can even stash new files if you stage them first (using the git add command).

If you want to stash changes to specific files rather than all your changes you can use the push sub-command like shown in the below example:

$ git status
On branch trunk
Your branch is up to date with 'origin/trunk'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   README.txt

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        FILE1.txt
        FILE2.txt
        FILE3.txt

no changes added to commit (use "git add" and/or "git commit -a")
$ git add .
$ git status
On branch trunk
Your branch is up to date with 'origin/trunk'.

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        new file:   FILE1.txt
        new file:   FILE2.txt
        new file:   FILE3.txt
        modified:   README.txt

$ git stash push README.txt FILE1.txt
Saved working directory and index state WIP on trunk: d2bcd85 Initial commit
$ git status
On branch trunk
Your branch is up to date with 'origin/trunk'.

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        new file:   FILE2.txt
        new file:   FILE3.txt

Restoring your stashed changes works as it normally would (using git stash pop).

Using the Rails router elsewhere

When working on Rails projects a commonly used part is the Rails router which is used to direct incoming requests to the appropriate controllers and actions and to generate paths and URLs so you don’t have to hardcode them all over the place.

In systems tests and integration tests the Rails router is also available for you to direct your tests to the appropriate URLs, in your regular tests or the Rails console however this is not the case. You can however get access to it by including a module that Rails can generate for you, if you call Rails.application.routes.url_helpers a module is returned that provides the Rails router’s methods.

Continue reading “Using the Rails router elsewhere”

Changing your default kernel

A while back my laptop running Ubuntu started hanging on boot after a kernel update, to make it work I had to revert to using an earlier kernel version from the boot screen.

Its a bit inconvenient to have to do this manually every time you boot your machine, you can however change the default boot option that is used by grub. You can do this by editing /etc/default/grub and setting GRUB_DEFAULT to the item to select and then running sudo update-grub.

Continue reading “Changing your default kernel”

Testing ActiveSupport concern modules

Using modules to share code between classes in Ruby is a commonly used method to add re-usable behaviour without blocking the inheritance chain, the Rails ActiveSupport::Concern adds some convenience methods to do so. What (at least in my opinion) should not be forgotten is to test the usage of such modules on your classes, this can actually be achieved fairly easily creating a module with test code that you can then again include in your tests.

Take this very contrived example module which adds an instance method to the classes it is included in:

module ReverseName  
  def reversed_name 
    name.reverse    
  end               
end                 

It’s function could be tested with the following test:

test 'reverse name' do                             
  assert_equal 'htimS nhoJ', @name_reversable.reversed_name 
end                                                

This can be poured into a module using ActiveSupport::Concern that can be included in test cases of other classes like so:

module Concerns                                          
  module ReverseNameTest                                 
    include ActiveSupport::Concern                       
                                                         
    included do                                          
      test 'reverse name' do                             
        assert_equal 'htimS nhoJ', @name_reversable.reversed_name 
      end                                                
    end                                                  
  end                                                    
end                                                      

In Rails projects I usually put shared test code inside the directory test/test_helpers, to have these loaded when running tests you will have to add the following line to your test_helper.rb:

Dir[Rails.root.join('test/test_helpers/**/*.rb')].sort
                                                 .each { |file| require file }

To now use this test module on a class that can make use of it we can include the test module in that model’s test like so:

require 'test_helper'                                             
                                                                  
class ContactTest < ActiveSupport::TestCase                       
  include Concerns::ReverseNameTest                               
                                                                  
  setup do                                                        
    @name_reversable = Contact.new(first_name: 'John', last_name: 'Smith') 
  end                                                             
                                                                  
  test 'name' do                                                  
    contact = Contact.new(first_name: 'John', last_name: 'Smith') 
    assert_equal 'John Smith', contact.name                       
  end                                                             
end                                                               

If you want to verify that the test gets executed for your model you can purposely break the test(s) to see them fail like shown below:

Running ActiveJobs inline temporarily

Pushing execution of code that take a long time to complete to ActiveJob can be great to increase the (feeling of) responsiveness for any Rails application. Sometimes it can be desirable to run triggered jobs inline instead though (in certain rake tasks for example), you can do this by overriding the queue adapter with the inline adapter like so:

ActiveJob::Base.queue_adapter = ActiveJob::QueueAdapters::InlineAdapter.new

If you want to ensure that the adapter is switched back to its original setting after you are done (because more code is executed around the part where you want to run the jobs inline) you can that using ensure like in the below example rake task:

desc 'My rake task'
task my_task: :environment do
  old_queue_adapter = ActiveJob::Base.queue_adapter
  ActiveJob::Base.queue_adapter = ActiveJob::QueueAdapters::InlineAdapter.new
  # your code here
ensure
  ActiveJob::Base.queue_adapter = old_queue_adapter
end

Note that if you are using different queueing backends for specific jobs (as documented in the Rails guide here) you would have to override each one of those too in the same way (if you would want to run those inline that is).

Vim tip: excluding files and paths from searches with Grepper

Grepper is a plugin for Vim to search your project asynchronously using your preferred search tool. By default Grepper will search Vim’s current directory and its subdirectories, in many projects that I work on this includes things I generally do not want to search in (with directories container vendor libraries such as node_modules).

You can pass extra options for the tool of your choice to the Grepper commands, ripgrep (which is what I use) supports a glob argument which you can use to exclude paths (and files) like so:

:GrepperRg --glob '!vendor' --glob '!node_modules' --glob '!public' --glob '!test/vcr_cassettes' 'Hello Word'

To prevent yourself from typing a ton of globs each time you want to search you can add a command to your vimrc for common combinations like so:

command! -nargs=+ -complete=file Search :GrepperRg --glob '!vendor' --glob '!node_modules' --glob '!public' --glob '!doc'

The above snippet adds a Search command to vim which excludes paths I generally do not want to search within in Rails projects which you can use like so:

:Search 'Hello World'

Rails: ActiveRecord descendants in development mode

Single table inheritance (often referenced to as STI) is a feature offered by Rails’s ActiveRecord (which is documented here) that allows you to subclass models to store data for multiple similar models in one database table. This can be a very useful feature under the right circumstances.

When working with Rails in development mode classes are not preloaded (unlike is done in production mode). If you use the descendants method to get a list of the subtypes of your model (to for example display them or to populate a select box) it is possible that sometimes an empty or partial list is returned rather than a list of all the defined subtypes (unless you have actually used one of them so far).

If you are working in a team this can be an especially devious little problem that can linger for a long time. Different developers may have different sets of data in their development system. Loading a list of STI models will load the subtype classes making them available in the application from that point on. If the database however does not contain records for the subtype’s class and you are not directly referencing it you will not see it. This can then result in one developer experiencing issues while the another does not.

In this article I will demonstrate the issue and offer a solution that you can implement.

Continue reading “Rails: ActiveRecord descendants in development mode”

Prepend to an existing rake task

Rake is a commonly used tool in Ruby projects to provide command line tasks, Rails comes with a number of rake tasks included for example. It is quite well documented how to write rake tasks, a while ago however I needed to prepend something to an existing rake task. One way to achieve this is to write a new rake task that executes the code that you want to execute and then calls the existing rake task. The (perhaps obvious) downside to this method is that you have to execute another rake task than you usually would.

It turns out that there is another way, you can use the enhance method on an existing rake task. In this article I will briefly explore how you can use this method.

Continue reading “Prepend to an existing rake task”