Created
June 8, 2012 10:02
-
-
Save gioele/2894800 to your computer and use it in GitHub Desktop.
define_method on modules
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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