Module: InjectableDependencies

Extended by:
ActiveSupport::Concern
Defined in:
lib/injectable_dependencies.rb,
lib/injectable_dependencies/version.rb

Overview

Allows classes to define instance methods that will be evaluated at runtime. (The implementation exploits Ruby’s method lookup.)

By default, dependencies declared at the class level will be made available to all instances of the class (note the call to .define_method in ClassMethods::Dependency).

Individual instances of including classes, however, may define their own singleton methods based on values provided when the object is initialized. NOTE: For this behavior to work, including classes must invoke #initialize_dependencies before the dependency methods are called. (A good place to do this is probably in your #initialize method, but if you want to do something weird, hey, you can.)

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

UndeclaredDependencyError =
Class.new(StandardError)
MissingImplementationError =
Class.new(StandardError)
VERSION =
"1.3.0"

Instance Method Summary collapse

Instance Method Details

#initialize(opts = {}) ⇒ Object



45
46
47
48
# File 'lib/injectable_dependencies.rb', line 45

def initialize(opts={})
  dependencies = opts[:dependencies] || {}
  initialize_dependencies(dependencies)
end

#initialize_dependencies(overrides = {}) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/injectable_dependencies.rb', line 50

def initialize_dependencies(overrides = {})
  return unless overrides
  self.class.send(:no_default_dependencies).each do |name|
    unless overrides.has_key?(name)
      raise MissingImplementationError.new("No implementation was provided for dependency ##{name}")
    end
  end
  overrides.each do |k,v|
    unless self.class.send(:dependencies).include?(k)
      raise UndeclaredDependencyError, "Cannot override undeclared dependency '#{k}'."
    end
    singleton_class.send(:define_method, k) { v } # available to this instance only
  end
end