Last active
December 25, 2015 13:59
-
-
Save arion/6987617 to your computer and use it in GitHub Desktop.
created by http://mediumexposure.com/multiple-table-inheritance-active-record/ with some modifications For use add to your model: include InheritedProperties inherits_properties_from 'SomePropertiesClass'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module InheritedProperties | |
extend ActiveSupport::Concern | |
included do | |
end | |
def properties_with_autobuild | |
properties_without_autobuild || build_properties | |
end | |
def method_missing(meth, *args, &blk) | |
properties.send(meth, *args, &blk) | |
rescue NoMethodError | |
super | |
end | |
module ClassMethods | |
def inherits_properties_from(association_class_name) | |
has_one :properties, class_name: association_class_name, autosave: true, inverse_of: model_name.underscore.to_sym | |
validate :properties_must_be_valid | |
alias_method_chain :properties, :autobuild | |
extend ClassMethods | |
define_properties_accessors(association_class_name.constantize) | |
end | |
def define_properties_accessors(association_class) | |
all_attributes = association_class.table_exists? ? association_class.content_columns.map(&:name) : [] | |
ignored_attributes = %w[] | |
attributes_to_delegate = all_attributes - ignored_attributes | |
attributes_to_delegate.each do |attrib| | |
class_eval <<-RUBY | |
def #{attrib} | |
properties.#{attrib} | |
end | |
def #{attrib}=(value) | |
self.properties.#{attrib} = value | |
end | |
def #{attrib}? | |
self.properties.#{attrib}? | |
end | |
RUBY | |
end | |
end | |
end | |
protected | |
def properties_must_be_valid | |
unless properties.valid? | |
properties.errors.each do |attr, message| | |
errors.add(attr, message) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment