Skip to content

Instantly share code, notes, and snippets.

@robinclart
Created August 20, 2012 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robinclart/3405958 to your computer and use it in GitHub Desktop.
Save robinclart/3405958 to your computer and use it in GitHub Desktop.
ridiculous
require "active_support/all"
require "active_model/naming"
class SuperFoo
A_CONSTANT = 3.14
def greet
puts "Hi! + #{A_CONSTANT}"
end
def self.class_method
puts "This is a class method"
end
end
module ClassWrapper
def self.extended(base)
base.class_eval do
alias_method :class_without_wrapper, :class
alias_method :class, :class_with_wrapper
end
end
def class_with_wrapper
@_class_with_wrapper ||= ClassWrapper.const_set class_without_wrapper.name, Class.new(class_without_wrapper) {
class << self
def name
super.gsub("ClassWrapper::", "")
end
alias_method :to_s, :name
end
}
end
end
x = SuperFoo.new
y = SuperFoo.new
y.extend ClassWrapper
y.class.extend ActiveModel::Naming
#instance methods work
x.greet
y.greet
#class methods work
x.class.class_method
y.class.class_method
#Name works (with the wrapper though)
puts y.class.model_name
puts x.class.model_name
# ~> -:51:in `<main>': undefined method `model_name' for SuperFoo:Class (NoMethodError)
# >> Hi! + 3.14
# >> Hi! + 3.14
# >> This is a class method
# >> This is a class method
# >> SuperFoo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment