AdamNYC
AdamNYC

Reputation: 20415

Create new classes or overloading with type in Rails

I have a Meeting model, with multiple Participants in different roles (say, Tutor and Student). Right now, I have a single class Participant, which has attribute :type with two possible values (Tutor/Student). These two types share some exactly the same methods. Each also has its own version of other methods. (say, a Tutor when schedule a meeting must get approval from Director). I handle the differences in methods by overloading with type:

def make_appointment
  do stuff
  if type = "Tutor" 
    do something extra
  end
end;

I am undecided whether to go this way, or to have two classes, Tutor and Student that inherit Participant class.

What are the issues/pitfalls should I consider in deciding which way to implement this?

Thank you.

Upvotes: 0

Views: 79

Answers (2)

Dave Newton
Dave Newton

Reputation: 160191

For methods that differ only slightly, there are options--build in extension points, pass blocks around to enhance behavior, etc.

Almost every time there's type-dependent behavior implemented via type comparisons it's not a good idea.

Upvotes: 1

davidb
davidb

Reputation: 8954

You should use some authorization gem like cancan which is the most poular.

There is a short tutorial about role based authorization. => https://github.com/ryanb/cancan/wiki/Role-Based-Authorization

Its absolutly okay to store the data in one Model. If there are many different attributes you may use polymorpic associations to expand the user Model but in most cases thats not needed!

Upvotes: 0

Related Questions