Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
module ActsAsClassMethod
unless respond_to? :metaclass
define_method :metaclass do
class << self; self; end
end
end
def acts_as_class_method(*methods)
methods.each do |method|
metaclass.send :define_method, method do |*params|
self.new(*params).send(method)
end
end
end
Object.extend ActsAsClassMethod
end
class Mailer
acts_as_class_method :send_mail!
def initialize(params={})
@from = params[:from]
@to = params[:to]
end
def send_mail!
puts "Sent mail from <#{@from}> to <#{@to}>"
end
end
Mailer.send_mail! :from => "admin@example.com", :to => "rondy@example.com"
@rondy

This comment has been minimized.

Copy link
Owner Author

rondy commented Oct 26, 2011

Ruby 1.9 defines "define_singleton_method", so you don't need to use metaclass.

def acts_as_class_method(*methods)  
  methods.each do |method|
    define_singleton_method method do |*params|
      self.new(*params).send(method)
    end
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.