Ruby module that facilitates English-like type checking in an inheritance hierarchy via "type_name?" methods
MIT License
Although polymorphism is a recommended standard in Object-Oriented programming for invoking varied behavior in an inheritance hierarchy, sometimes it is still useful to verify if a particular model belongs to a certain type when the behavior concerned does not belong to the model and is too small to require a Design Pattern like Strategy.
A common example in Rails is checking user roles before rendering certain parts of the view:
<% if user.is_a?(Admin) %>
<%= link_to 'Admin', admin_dashboard_path %>
<% end %>
<% if user.is_a?(Customer) %>
<%= link_to 'Customer Profile', customer_profile_path %>
<% end %>
To avoid the model.is_a?(Admin)
syntax, a more readable approach
that developers resort to is to add an English-like DSL method that hides the
details of Object-Oriented type checking: model.admin?
.
The Rails example above would then become:
<% if user.admin? %>
<%= link_to 'Admin', admin_dashboard_path %>
<% end %>
<% if user.customer? %>
<%= link_to 'Customer Profile', customer_profile_path %>
<% end %>
Implementing such methods manually gets repetitive and error-prone, so an easier
way to get these methods automatically is to mixin the EasilyTypable
module.
require 'easily_typable' # in IRB at cloned project directory, call this instead: require './lib/easily_typable'
class Vehicle
include EasilyTypable
end
class Car < Vehicle
end
class Truck < Vehicle
end
class Van < Vehicle
end
puts Car.new.vehicle? # prints true
puts Car.new.car? # prints true
puts Car.new.truck? # prints false
puts Car.new.van? # prints false
puts Truck.new.vehicle? # prints true
puts Truck.new.car? # prints false
puts Truck.new.truck? # prints true
puts Truck.new.van? # prints false
puts Van.new.vehicle? # prints true
puts Van.new.car? # prints false
puts Van.new.truck? # prints false
puts Van.new.van? # prints true