Ognjen Regoje bio photo

Ognjen Regoje
But you can call me Oggy


I make things that run on the web (mostly).
More ABOUT me and my PROJECTS.

me@ognjen.io LinkedIn

Automatically creating plural models in Rails

#pattern #rails

At times it’s more readable to use the plural of a model instead of singular. For instance Products.for_indexing instead of Product.for_indexing. This can be accomplished through a simple initializer that creates the plural model automatically.

It looks like this:

# config/initializers/pluralize.rb
module Pluralize

  # list of models that should have the plural form
  to_pluralize = [
    Product
  ].freeze

  to_pluralize.each do |c|
    # get the plural name of the class
    plural = c.name.pluralize

    # create a new class within the Object module,
    # and inherit from the non-plural version
    Object.const_set(plural, Class.new(c))

    # optionally, add functionality such as a scope
    # that would only exist on the plural version
    plural.constantize.class_eval do
      scope :that_are, -> { where('1=1') }
    end

  end
end

That creates the Products class that inherits from Product.

Now, I can do Products.for_indexing as well as Product.for_indexing.

When the plural class is created you can also add additional functionality. The example above adds the scope that_are as an example. Products.that_are would work, whereas Product.that_are wouldn’t.

Limitations

  • Convention dictates that model name should be singular
    • However, for some models you would rarely operate on the individual entry
    • Consider, for instance, a Stat model.
  • .class == will not work for records retrieved with the plural version
    • is_a? works correctly, however
    • Products.first == Product => false
    • Products.first.is_a? Product => true