Skip to content

Instantly share code, notes, and snippets.

@vasilakisfil
Last active August 29, 2015 14:07
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 vasilakisfil/42aa81cadc00b2533c90 to your computer and use it in GitHub Desktop.
Save vasilakisfil/42aa81cadc00b2533c90 to your computer and use it in GitHub Desktop.
namespaced mixins
#Mixins as I sometimes want them. Proper Composition.
#It probably requires different approach on how we write mixins atm.
#@vasilakisfil
module NamespacedMixin
module ClassMethods
def namespace(name, as:)
namespace = as
namespaced_class = name.split('::').inject(Object) {|o,c| o.const_get c}
cls = Class.new{
include namespaced_class
}.new
define_method("#{namespace}") do
cls
end
end
end
def self.included(base)
base.extend(ClassMethods)
end
end
module TestModule1
def do_that
puts 'Doing that'
end
def do_other
puts 'Doing that'
end
end
module TestModule2
def do_that
puts 'Do this and that'
end
end
module TestModule
module NestedModule
def do_that
puts 'Do everything'
end
end
end
class Example
include NamespacedMixin
namespace 'TestModule1', as: :simply
namespace 'TestModule2', as: :namespaced
namespace 'TestModule::NestedModule', as: :mixins
end
ex = Example.new
ex.simply.do_that
ex.mixins.do_that
ex.namespaced.do_that
##output##
#Doing that
#Do everything
#Do this and that
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment