Skip to content

Instantly share code, notes, and snippets.

@daicoden
Last active December 19, 2015 00:39
Show Gist options
  • Save daicoden/5869816 to your computer and use it in GitHub Desktop.
Save daicoden/5869816 to your computer and use it in GitHub Desktop.
Minecart Injectable
module Minecart
module Injectable
module ClassMethods
# USAGE
# @param field
# The name of the instance variable to set with the injected value
# @param opts
# :with - a ruby java class i.e. (java.lang.String) which the config value can be cast into.
# :named - a string which will be used to retrieve an object annotated with the @Named convention.
# :annotated - a ruby java binding annotation which is used to retrieve the requested object
def inject(field, opts = {})
attr_reader field
injections[field] = opts
end
def new(*args)
res = injectable_original_new(*args)
res.injectable_process_injections(Minecart::Injectable.injector)
res
end
def injections
@injections ||= {}
end
end
def self.injector
@injector || raise("No Injector :(")
end
def self.with_injector(injector)
original = @injector
@injector = injector
yield
ensure
@injector = original
end
def self.set_injector(injector)
@injector = injector
end
def self.included(base)
base.class.__send__(:alias_method, :injectable_original_new, :new)
base.extend ClassMethods
end
def injectable_process_injections(injector)
self.class.injections.each do |field_name, opts|
klass = opts[:with]
if opts[:named]
key = com.google.inject.Key.get(klass.java_class, com.google.inject.name.Names.named(opts[:named]))
elsif opts[:annotated]
key = com.google.inject.Key.get(klass.java_class, opts[:annotated].java_class)
else
key = klass.java_class
end
instance = injector.getInstance(key)
instance_variable_set(:"@#{field_name}", instance)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment