Skip to content

Commit

Permalink
move all private methods in to an object
Browse files Browse the repository at this point in the history
  • Loading branch information
krisleech committed Feb 13, 2015
1 parent 191f6ca commit 9542587
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 30 deletions.
32 changes: 2 additions & 30 deletions lib/medicine.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
require "medicine/version"
require "medicine/dependencies"
require "medicine/injections"
require "medicine/define_methods"
require "inflecto"

module Medicine
Expand All @@ -24,41 +25,12 @@ def self.prepended(base)
# @example
# new(user_repo: User, role_repo: Role)
def initialize(*args)
@injections = Injections.new(last_hash(args))
assert_all_dependencies_met
define_dependency_methods
DefineMethods.on(self, args)
super
end

private

def last_hash(args)
args.last.respond_to?(:[]) ? args.pop : {}
end

def assert_all_dependencies_met
raise RequiredDependencyError, "pass all required dependencies (#{unmet_dependencies.join(', ')}) in to initialize" unless unmet_dependencies.empty?
end

def define_dependency_methods
dependencies.each do |dependency|
define_singleton_method dependency.method_name do
@injections.fetch(dependency.name) { dependency.default }
end
self.singleton_class.class_eval { private dependency.method_name }
end
end

def unmet_dependencies
dependencies.without_default.select do |dependency|
!@injections.include?(dependency.name)
end
end

def dependencies
self.class.dependencies
end

module ClassMethods
def dependencies
@dependencies ||= Dependencies.new
Expand Down
42 changes: 42 additions & 0 deletions lib/medicine/define_methods.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
module Medicine
class DefineMethods
def self.on(object, injections)
new(object, injections).call
end

def initialize(object, args)
@object = object
@dependencies = object.class.dependencies
@injections = Injections.new(last_hash(args))
end

def call
assert_all_dependencies_met
object.instance_variable_set("@injections", injections)
dependencies.each do |dependency|
object.define_singleton_method dependency.method_name do
@injections.fetch(dependency.name) { dependency.default }
end
object.singleton_class.class_eval { private dependency.method_name }
end
end

private

attr_reader :object, :dependencies, :injections

def assert_all_dependencies_met
raise RequiredDependencyError, "pass all required dependencies (#{unmet_dependencies.join(', ')}) in to initialize" unless unmet_dependencies.empty?
end

def unmet_dependencies
dependencies.without_default.select do |dependency|
!injections.include?(dependency.name)
end
end

def last_hash(args)
args.last.respond_to?(:[]) ? args.pop : {}
end
end
end

0 comments on commit 9542587

Please sign in to comment.