Skip to content

Migrate action_filter in Ruby on Rails Has Fix

Description

This rule is used to migrate {before,after,around}_filter to {before,after,around}_action in Ruby on Rails controllers.

These are methods that run before, after or around an action is executed, and they can be used to check permissions, set variables, redirect requests, log events, etc. However, these methods are deprecated in Rails 5.0 and will be removed in Rails 5.1. {before,after,around}_action are the new syntax for the same functionality.

This rule will replace all occurrences of {before,after,around}_filter with {before,after,around}_action in the controller code.

YAML

yaml
id: migration-action-filter
language: ruby
rule:
  any:
    - pattern: before_filter $$$ACTION
    - pattern: around_filter $$$ACTION
    - pattern: after_filter $$$ACTION
  has:
    pattern: $FILTER
    field: method
fix:
  $NEW_ACTION $$$ACTION
transform:
  NEW_ACTION:
    replace:
      source: $FILTER
      replace: _filter
      by: _action

Example

rb
class TodosController < ApplicationController
  before_filter :authenticate
  around_filter :wrap_in_transaction, only: :show
  after_filter do |controller|
    flash[:error] = "You must be logged in"
  end

  def index
    @todos = Todo.all
  end
end

Diff

rb
class TodosController < ApplicationController
  before_action :authenticate
  before_filter :authenticate
  around_action :wrap_in_transaction, only: :show
  around_filter :wrap_in_transaction, only: :show
  after_action do |controller|  
     flash[:error] = "You must be logged in"
  end
  after_filter do |controller| 
    flash[:error] = "You must be logged in"
  end

  def index
    @todos = Todo.all
  end
end

Contributed by

Herrington Darkholme, inspired by Future of Ruby - AST Tooling.

Made with ❤️ with Rust