Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass value to parent in class declaration in Ruby

Tags:

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.

like image 836
Kormie Avatar asked Aug 18 '12 05:08

Kormie


1 Answers

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
like image 157
Stefan Avatar answered Oct 19 '22 22:10

Stefan