Skip to content

Instantly share code, notes, and snippets.

@ifesdjeen
Created May 6, 2012 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ifesdjeen/2623624 to your computer and use it in GitHub Desktop.
Save ifesdjeen/2623624 to your computer and use it in GitHub Desktop.
metaprogramming magic
module SafeConstDefinition
extend ActiveSupport::Concern
module ClassMethods
def const_missing(name)
puts "Warning: #{name} was not defined, assuming further definition. Keep calm tho."
# Since Parent is defined after Child both in root and in SomeModule,
# i need to have a mechanism to define a future const, but simple:
# const_set(name, Class.new)
# doesn't do the thing, since it defines the constant within the class
# rather than enclosing module
end
end
included do
extend SafeConstDefinition::ClassMethods
end
end
module SomeModule
class Child
include SafeConstDefinition
attribute :parent, Parent
end
class Parent
include SafeConstDefinition
attribute :child, Child
end
end
class Child
include SafeConstDefinition
attribute :parent, Parent
end
class Parent
include SafeConstDefinition
attribute :child, Child
end
@ifesdjeen
Copy link
Author

Seems that

      def parent_name
        name =~ /::[^:]+\Z/ ? $`.freeze : nil
      end

      def const_missing(name)
        puts "Warning: #{name} was not defined, assuming further definition. Keep calm tho."
        if parent_name.nil?
          Object.const_set(name, Class.new)
        else
          puts parent_name
          const_get(parent_name).const_set(name, Class.new)
        end
      end

did the trick!

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