Today I was searching on a means for mixing in a namespaced class into another class and stumbled onto a gist of mine that I had saved back in October 2013.
Here's what I implemented today, and you'll find a link to the original Gist at the end of this post.
The essence of the approach is to simply call const_set
on the base class, _klass
, and in this example setting that constant to class of interest via Class.new(ClassOfInterest)
.
You would also see this being used in specs such as
MyFancyException = Class.new(StandardError)
raise MyFancyException
In this context, the receiver, self
is in fact the class in which you call the above, so self.MyFancyException = Class.new(StandardError)
would also be perfectly fine, although not strictly idiomatic Ruby, as most often the receiver is implicit.
module Snowden
module Utility
extend self
class Response
attr_reader :error_message
def initialize(success: nil, error_message: nil)
@success = success
@error_message = error_message
end
def success?
@success
end
def self.success
new(success: true)
end
def self.failure(error_message)
new(success: false, error_message: error_message)
end
end
module ResponseMixin
class << self
def included _klass
response = Class.new(Utility::Response)
_klass.const_set :Response, response
end
end
end
end
end
Ref: Gist