Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing class names in database to mimic a design pattern - Ruby on Rails

I was looking for implementing strategy design pattern in one of my project which is on rails. Basically I have to call methods on objects that are differentiated by a single field in the database, and this difference will ensure different method behavior.

After some study, I found that ruby rarely requires design patterns and that it uses the duck-typing. Now to achieve the same affect, I am thinking about storing class names in the database and call the methods of that class when required. Like this,

duckOne = Duck.find(id)
duckOne[:className].fly(duckOne) #This scenario is same as Class.fly,but class is coming from db

duckTwo = Duck.find(id)
duckTwo[:className].fly(duckTwo) #Similar to above, just a different class from database

Is there a better way to do it? And is this approach correct?

like image 266
Anss Avatar asked Jan 30 '26 03:01

Anss


1 Answers

Basically, from what you've described, I think you're looking for Single Table Inheritance (STI) (you may have to scroll to find the info).

With STI you use one database table to represent multiple classes that derive from the same superclass. Rails uses a column called type to know which class to interpret the db row as.

You can still use the find method on the superclass to find all kinds of subclassing models.

For example:

class Bird < ActiveRecord::Base
  def quack
    "quack"
  end
end

class Duck < Bird
  def quack
    "foo"
  end
end

class Goose < Bird
  def quack
    "bar"
  end
end

duck = Duck.create
goose = Goose.create

Bird.find(duck.id).quack
# => "foo"
Bird.find(goose.id).quack
# => "bar"
like image 123
Jesper Avatar answered Jan 31 '26 18:01

Jesper