Last active
August 29, 2015 14:07
-
-
Save vasilakisfil/42aa81cadc00b2533c90 to your computer and use it in GitHub Desktop.
namespaced mixins
This file contains hidden or 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
#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