3

In Ruby on Rails 5.2, migration files contain a class that looks like this.

class MyMigration < ActiveRecord::Migration[5.2]

I know that the [5.2] syntax is specifying what version of rails the migration targets, but I don't understand how this works. Migration[5.2] is not a valid Ruby class name.

What is this square bracket syntax, and how is it not causing ruby syntax errors?

1 Answers1

4

Ruby objects can have [] methods. They are used in the Array class, but any class can implement them.

def []()
  ...
end

Since classes are full objects, they too can have square bracket methods.

Marlin Pierce
  • 9,931
  • 4
  • 30
  • 52
  • I see. So that method would return a Class object allowing MyMigration to subclass it? – fourseventy Jun 13 '18 at 19:56
  • @fourseventy It could return anything it wanted, but if it wasn't returning a `Migration` implementation it'd be counter-intuitive. – Dave Newton Jun 13 '18 at 19:57
  • 1
    @DaveNewton: And if it doesn't return an instance of `Class`, it'll be a `TypeError`. – Jörg W Mittag Jun 13 '18 at 22:12
  • 2
    @fourseventy: I think the piece of the puzzle you are missing is that you are (wrongly) assuming that the code to the right of `<` has to be a "class name". Actually, classes in Ruby don't *have* names (at least not in the Java sense of the word). A class is simply an object like any other object. So, the code to the right of the `<` is simply *executable Ruby code* that evaluates to an instance of the `Class` class. You could put something like `[Array, Hash].sample` there, and your class would randomly inherit from either `Array` or `Hash`! – Jörg W Mittag Jun 13 '18 at 22:15
  • @JörgWMittag That's what all my code does. Makes things more interesting. – Dave Newton Jun 13 '18 at 22:32
  • @JörgWMittag Thanks for your comment. It helped me understand something. SO should give an option to bookmark/star comments. – Tanmay Jul 17 '19 at 04:54