Skip to content

Instantly share code, notes, and snippets.

@sxross
Last active December 18, 2015 04:09
Show Gist options
  • Save sxross/5723831 to your computer and use it in GitHub Desktop.
Save sxross/5723831 to your computer and use it in GitHub Desktop.
Demonstrates inheritance of singleton vars (@@vars)
module MotionModel
module Model
def self.included(base)
base.extend(PublicClassMethods)
end
module PublicClassMethods
def inherited(subclass)
p "inherited from #{subclass}"
end
end
end
end
class MyModel
include MotionModel::Model
@@attribute = {model: "MyModel", other_stuff: {name: 'whatever'}}
def attr
p "attribute: #{@@attribute}"
end
end
my_model = MyModel.new
my_model.attr
class MySubclass < MyModel
@@attribute = {model: "MySubclass", other_stuff: {name: 'something else'}}
end
my_model = MyModel.new
my_model.attr
my_subclass = MySubclass.new
my_model.attr
my_subclass.attr
@DougPuchalski
Copy link

Here's an example using singleton instance variables which are clone when inherited.

module MotionModel
  module Model
    def self.included(base)
      base.extend(PublicClassMethods)
    end

    module PublicClassMethods
      attr_accessor :attrs

      def attrs
        @attrs ||= {}
      end

      def inherited(subclass)
        p "inherited from #{subclass}"
        subclass.attrs = attrs.dup
      end
    end
  end
end

class MyModel
  include MotionModel::Model

  self.attrs = {model: "MyModel", other_stuff: {name: 'whatever'}}

  def attrs
    p "attribute: #{attrs}"
    attrs
  end
end

my_model    = MyModel.new
my_model.class.attrs

class MySubclass < MyModel
end

class MySubclass2 < MyModel
  self.attrs = {model: "MySubclass", other_stuff: {name: 'something else'}}
end

my_model    = MyModel.new
my_subclass = MySubclass.new
my_subclass2 = MySubclass2.new
my_model.class.attrs
my_subclass.class.attrs
my_subclass2.class.attrs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment