I just published a new gem, inherited-attributes, for Active Record that works with the Ancestry gem to provide a tree data structure the ability to inherit attributes from their parent node, or farther up the tree. We’ve been using this technique for a long time to support configuring our multi-tenant application.
Once the gem is installed, its very simple to configure:
ActiveRecord::Schema.define do create_table :nodes, :force => true do |t| t.string :name t.string :value t.string :ancestry, :index => true end end class Node < ActiveRecord::Base has_ancestry inherited_attribute :value end
From there, you can access the effective attributes which look up the tree ancestry to find a value to inherit.
root = Node.create! child = Node.create!(:parent => root, :value => 12) grandchild = Node.create!(:parent => child) root.effective_value # nil child.effective_value # 12 grandchild.effective_value # 12 -- inherited from child
There are more options and examples in the gem, including has-one relationships, default values and support for enumerations.
We’ve found it helpful and writing a gem made this code much easier to test. What code do you have that would be easier to test as a gem or would be useful to others?