Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Rails: Polymorphism through 'constantize'

DZone's Guide to

Rails: Polymorphism through 'constantize'

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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
     widget_name.constantize.new(params)
  end
 
  def widget_name
    "#{params[:widget_name]}_widget".camelize
  end
end

Where the individual widget classes would be like this:

class FooWidget
 
end
class BarWidget
 
end

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.

 

 

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Published at DZone with permission of Mark Needham, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}