Kormie
Kormie

Reputation: 127

Pass value to parent in class declaration in Ruby

I was watching a screencast with Jim Weirich where he started to do something like this:

class Subuser < User("Type")
end

Does Ruby let you pass arguments when defining a parent class? I can't come up with an example where that would actually work.

Upvotes: 5

Views: 97

Answers (1)

Stefan
Stefan

Reputation: 114178

You can do that by declaring a method User which takes an argument and returns a class:

class Admin
end

class Client
end

def User(arg)
  case arg
    when :admin
      Admin
    when :client
      Client
  end
end

class Subuser < User(:admin)
end

Subuser.superclass
# => Admin

Upvotes: 7

Related Questions