Skip to content

Instantly share code, notes, and snippets.

@rondy
Created October 26, 2011 13:02
Show Gist options
  • Save rondy/1316279 to your computer and use it in GitHub Desktop.
Save rondy/1316279 to your computer and use it in GitHub Desktop.
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
Copy link
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