Skip to content

Instantly share code, notes, and snippets.

@gioele
Created June 8, 2012 10:02
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 gioele/2894800 to your computer and use it in GitHub Desktop.
Save gioele/2894800 to your computer and use it in GitHub Desktop.
define_method on modules
#!/usr/bin/ruby1.8
class Main
module Extra
def self.define_fancy_method(method_name)
define_method(method_name) do |arg|
return [arg, arg].join(self.separator)
end
end
end
module M1
extend Extra
Extra.define_fancy_method :foo
end
module M2
extend Extra
Extra.define_fancy_method :faa
end
include M1
include M2
attr_accessor :separator
end
x = Main.new
x.separator = ','
puts x.foo('a') # => 'a,a'
puts x.faa('b') # => 'b,b'
#!/usr/bin/ruby1.8
class Main
module M1
def self.define_fancy_method(method_name)
define_method(method_name) do |arg|
return [arg, arg].join(self.separator)
end
end
define_fancy_method :foo
end
module M2
# copy and pasted from M1
def self.define_fancy_method(method_name)
define_method(method_name) do |arg|
return [arg, arg].join(self.separator)
end
end
define_fancy_method :faa
end
include M1
include M2
attr_accessor :separator
end
x = Main.new
x.separator = ','
puts x.foo('a') # => 'a,a'
puts x.faa('b') # => 'b,b'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment