polymorphic_model

Not everybody likes Single Table Ineritance or just not everywhere can be used. This is simple substitute for ActiveRecord’s STI mechanism. It uses defined column to determine object type.

Simple use case:

# migration:

create_table :configurations do |t|
  t.string :entry_type
  t.string :value
end

# model

class Configuration < ActiveRecord::Base
  polymorphic_model :with_type_column => :entry_type
  define_type :website_name, :singleton => true, :autocreate => true
  define_type :website_motto, :singleton => true
  define_type :author
end

# example usage

@name = Configuration.website_name.value
@authors = Configuration.author.map(&:value)

Configuration.author.create!(:value => "John Smith")

# this would throw exception (not valid)
# Configuration.create!(:entry_type => "website_name")

Configuration.website_motto
=> []
Configuration.website_motto.create(:value => "Hello world!")
Configuration.website_motto.value
=> "Hello world!"

This is just example. It can be used wherever STI is too drastically splits model file or more than one controller is not what you actually want. You can avoid also problems with polymorphic_path.

Note on Patches/Pull Requests

  • Fork the project.

  • Make your feature addition or bug fix.

  • Add tests for it. This is important so I don’t break it in a future version unintentionally.

  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but

    bump version in a commit by itself I can ignore when I pull)
    
  • Send me a pull request. Bonus points for topic branches.

Distributed under MIT license. See LICENSE for details.