2

Have not used Ruby in quite sometime and ran into some unfamiliar syntax:

class AddQuantityToLineItems < ActiveRecord::Migration[5.1]

The [5.1] seems to be forcing a particular ActiveRecord::Migration version? What is this syntax called and where can the documentation for it be found?

Thanks!

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
randombits
  • 47,058
  • 76
  • 251
  • 433
  • Take a look at this question of SO: https://stackoverflow.com/questions/38543894/ruby-grammar-name-for-number-after-subclass-of-one-class – JesusTinoco Aug 01 '17 at 22:05

1 Answers1

4

It's a familiar syntax, but it's unfamiliar in this location, that's all. The base class specifier is allowed to be an expression, which can include method calls.

Here's a way of re-creating that situation:

class CrazyProxyClass
  def [](v)
     Class.new
  end
end

CrazyMethod = CrazyProxyClass.new

class CrazyDerived < CrazyMethod[1.2]
end

CrazyDerived.new
# => CrazyDerived

You can also get even more adventurous:

class NormalBase
end

class DebugBase < NormalBase
end

class Example < (ENV['DEBUG'] ? DebugBase : NormalBase)
end

The only limit is your imagination and tools like Rubocop that will tell you it's probably a bad idea to get this nuts. The only real obligation is that whatever that expression returns is a Class or you'll get a "superclass must be a Class" exception.

tadman
  • 208,517
  • 23
  • 234
  • 262