Want more GoRails?

GoRails is packed full with 717 lessons just like this one.

Sign up to get full access or log in to your account and sit back.

The Ruby Subscript Operator

January 9, 2023

Track your progress

Sign in to track your progress and access subscription-only lessons.

Log In

Your Teacher

Hi, I'm Chris. I'm the creator of GoRails, Hatchbox.io and Jumpstart. I spend my time creating tutorials and tools to help Ruby on Rails developers build apps better and faster.

About This Episode

Rails uses the Ruby subscript operator to implement versioning with ActiveRecord Migrations. We'll learn how this works and implement it from scratch to see how it all ties together

Notes

Resources

module ActiveRecord
  class Migration

    # Receives a version of ActiveRecord as a float
    # Return a Class
    def self.[](version)
      class_name = "V#{version.to_s.gsub(".", "_")}" # => "V7_0"
      ActiveRecord.const_get(class_name)
    end

    def add_column(table_name, column_name, column_type)
      puts "Adding #{column_name} to #{table_name} table"
    end
  end

  class V7_0 < Migration
    def add_column(table_name, column_name, column_type)
      puts "Adding #{column_name} to #{table_name} table with old version 7.0"
    end
  end

  class V8_0 < Migration
  end
end

class AddEmailToUsers < ActiveRecord::Migration[7.0]
  def change
    add_column :users, :email, :string
  end
end

class AddNameToUsers < ActiveRecord::Migration[8.0]
  def change
    add_column :users, :name, :string
  end
end

AddEmailToUsers.new.change
AddNameToUsers.new.change

Want to stay up-to-date with Ruby on Rails?

Join 86,563+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.