Skip to content

Commit

Permalink
Merge pull request #5 from misfo/module_with
Browse files Browse the repository at this point in the history
Separate method selection from including/extending
  • Loading branch information
Alan Dipert committed May 6, 2012
2 parents e4adb97 + 31e9935 commit 8b7c94b
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 23 deletions.
6 changes: 2 additions & 4 deletions README.md
Expand Up @@ -24,10 +24,8 @@ module Statistics
end

class Main
include Rns

extend_specified Arithmetic => [:inc]
include_specified Statistics => [:avg]
extend Rns.module_with(Arithmetic => [:inc])
include Rns.module_with(Statistics => [:avg])

def main
puts "1+1 is #{self.class.inc 1} and the average of [1,2,3] is #{avg [1,2,3]}"
Expand Down
19 changes: 4 additions & 15 deletions lib/rns.rb
@@ -1,8 +1,4 @@
module Rns
def self.included(base)
base.extend(ClassMethods)
end

class << self
def f(m)
lambda{|*args| send(m, *args)}
Expand Down Expand Up @@ -42,6 +38,10 @@ def constant_for(module_names)
more.reduce(Kernel.const_get(m)){|m, s| m.const_get(s)}
end

def module_with(use_spec)
Module.new.tap {|m| add_methods(m, use_spec) }
end

def add_methods(to, use_spec)
use_spec.to_a.each do |from, sub_spec|
if (sub_spec.is_a? Hash)
Expand All @@ -64,17 +64,6 @@ def add_methods(to, use_spec)
end
end

module ClassMethods
def include_specified(use_spec)
Rns::add_methods(self, use_spec)
end

def extend_specified(use_spec)
singleton_class = class << self; self; end
Rns::add_methods(singleton_class, use_spec)
end
end

def self.using(use_spec, &blk)
blk[Object.new.tap{|o| Rns::add_methods(o.class, use_spec)}]
end
Expand Down
7 changes: 3 additions & 4 deletions spec/rns/rns_spec.rb
Expand Up @@ -19,11 +19,10 @@ def self.avg(arr); arr.reduce(:+).to_f / arr.count end
end
end

class Thing
include Rns

extend_specified Math::Arithmetic => [:inc]
include_specified Math::Statistics => [:avg]
class Thing
extend Rns.module_with(Math::Arithmetic => [:inc])
include Rns.module_with(Math::Statistics => [:avg])

def inced_one
self.class.inc 1
Expand Down

0 comments on commit 8b7c94b

Please sign in to comment.