All Lessons / The Ruby Subscript Operator

Want more GoRails?

GoRails is packed full with over 350 lessons just like this one.

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

The Ruby Subscript Operator

#476 ยท January 9, 2023

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

Discussion

Loading...
logo Created with Sketch.

Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

© 2023 GoRails, LLC. All rights reserved.