Abstract class

A

Ayyanar Aswathaman

How to create the abstract class and abstract method in ruby.
In RAILS active_record::base there is an attribute abstract_class.
How it is related to the ruby abstract class?
 
S

Stefan Lang

You don't need abstract classes or methods in Ruby.
If you want to share a bunch of methods between
classes, use a module. If the module depends on
other methods not in the module (these would be
abstract methods in a Java class model) say so
in the module documentation.

Ruby's builtin Enumerable module is a good example -
it provides a number of methods that depend only
on an existing "each" method.
 
T

Thomas Wieczorek

There is no keyword to create abstract classes, but you can force the
implementation of some methods if you need to.

class Foo
def bar
raise NotImplementedError
end
end

You will only get an exception at runtime, when something tries to
call it. So you should override it in a subclass.

class Bar < Foo
def bar
"Foobar"
end
end
 
F

Florian Gilcher

Don't think of this as a "true" abstract class.

It is a value that ActiveRecord uses to determine whether a child of
ActiveRecord::Base is a "true" model (and by that, has a database
table attached to it). This is not a language feature.

Greetings
Skade
 
R

Rick DeNatale

It is a value that ActiveRecord uses to determine whether a child of
ActiveRecord::Base is a "true" model (and by that, has a database
table attached to it). This is not a language feature.

Yes, it's very much an ActiveRecord thing. There are three different
uses of building an inheritance hierarcy for ActiveRecord models:

1) For using "single table inheritance" an ActiveRecord class and it's
subclasses all need to map to the same database table. AR does this
by mapping each class to a table based on it's highest non-abstract
ancestor or itself if it's superclass is itself abstract.

2) For providing common setup of multiple tables. One common use of
this is when you have multiple databases, with some tables in one and
some in another. Making an 'abstract' ActiveRecord class for tables
in a particular database to subclass, and setting the abstract class'
database connection is the standard way to do this.

3) Providing common methods. However, this is almost always better
achieved by using Ruby modules rather than inheritance.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,800
Messages
2,569,657
Members
45,417
Latest member
BonitaNile
Top