Over a million developers have joined DZone.

Rails: Polymorphism through 'constantize'

DZone's Guide to

Rails: Polymorphism through 'constantize'

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

One interesting feature of Rails which Shishir pointed out the other day is the ability to take a user provided value and make use of Active Support's 'constantize' method to effectively achieve polymorphism directly from the user's input.

As an example if we were creating different types of widgets from the same web page we might have several different forms that the user could submit.

We could have a hidden field representing the type of the widget like so:

<%= hidden_field_tag :widget_name, :foo  %>

And then when the form is submitted we can instantiate the appropriate widget class.

class WidgetController
  def some_action
  def widget_name

Where the individual widget classes would be like this:

class FooWidget
class BarWidget

The closest we'd get to doing this with C#/associated frameworks would be to create a dictionary with the widget name as the key and a function representing the object instantiation as the value.

Therefore if we wanted to add a new widget we'd still have to change the WidgetController whereas with the Rails solution we'd just have to change the HTML and add a new report which would then be automatically hooked up.

I'm sure there's some other clever things you can do with Rails that I don't yet know about but this struck me as one of those things that helps explain why it's possible to develop some web applications much more quickly with Rails than with other frameworks.



Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}