Skip to content

Instantly share code, notes, and snippets.

@reddyonrails
Created October 23, 2015 19:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reddyonrails/c5aa35efe3e8d3f333ef to your computer and use it in GitHub Desktop.
Save reddyonrails/c5aa35efe3e8d3f333ef to your computer and use it in GitHub Desktop.
Creating dynamic class with name space from string in Ruby
module Util
# Create Job class from ENV string
def self.create_job_class(name, queue_var)
klass = Class.new(ActiveJob::Base) do
queue_as ENV.fetch(queue_var, 'default')
end
create_dynamic_class(name, klass)
end
def self.create_dynamic_class(class_with_namescope, klass)
module_name, class_name = class_with_namescope.split('::')
if class_name.present? # class is inside a module
unless module_constant = Object.const_get(module_name) rescue nil
module_constant = Object.const_set(module_name, Module.new {})
end
module_constant.const_set(class_name, klass)
else
Object.const_set(module_name, klass) # module_name is now class_name
end
rescue Exception => e
raise "Please choose right job class #{class_with_namescope}"
end
# Get constant from string with namespaces
def self.find_constant(constant_with_namescope)
constant_with_namescope.split('::').inject(Module) { |path, findable| path.const_get(findable) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment