Difference between revisions of "Metaprogramming in Ruby"
Jump to navigation
Jump to search
PeterHarding (talk | contribs) (Created page with " =Reimplement attr_accessor= <pre> #!/usr/bin/env ruby module Accessor def my_attr_accessor(name) STDERR.print "#{name}\n" ivar_name = "@#{name}" define...") |
PeterHarding (talk | contribs) |
||
(4 intermediate revisions by the same user not shown) | |||
Line 6: | Line 6: | ||
module Accessor | module Accessor | ||
def my_attr_accessor(name) | def my_attr_accessor(name) | ||
ivar_name = "@#{name}" | |||
STDERR.print "#{name}\n" | STDERR.print "#{name}\n" | ||
define_method(name) do | define_method(name) do | ||
STDERR.print "Get #{name}\n" | STDERR.print "Get #{name}\n" | ||
instance_variable_get(ivar_name) | instance_variable_get(ivar_name) | ||
end | end | ||
define_method("#{name}=") do |val| | define_method("#{name}=") do |val| | ||
STDERR.print "Set #{name} = #{val}\n" | STDERR.print "Set #{name} = #{val}\n" | ||
instance_variable_set(ivar_name, val) | instance_variable_set(ivar_name, val) | ||
end | end | ||
end | end | ||
end | end | ||
Line 37: | Line 42: | ||
puts ex.tst | puts ex.tst | ||
</pre> | </pre> | ||
Output | |||
<pre> | |||
$ ./meta.rb | |||
var | |||
tst | |||
Set var = 99 | |||
Get var | |||
99 | |||
Set tst = 2 | |||
Get tst | |||
2 | |||
</pre> | |||
[[Category:Ruby]] | [[Category:Ruby]] | ||
[[Category:Examples]] | [[Category:Examples]] | ||
[[ | [[Category:Metaprogramming]] |
Latest revision as of 10:20, 30 July 2012
Reimplement attr_accessor
#!/usr/bin/env ruby module Accessor def my_attr_accessor(name) ivar_name = "@#{name}" STDERR.print "#{name}\n" define_method(name) do STDERR.print "Get #{name}\n" instance_variable_get(ivar_name) end define_method("#{name}=") do |val| STDERR.print "Set #{name} = #{val}\n" instance_variable_set(ivar_name, val) end end end class Example extend Accessor my_attr_accessor :var my_attr_accessor :tst end ex = Example.new ex.var = 99 puts ex.var ex.tst = 2 puts ex.tst
Output
$ ./meta.rb var tst Set var = 99 Get var 99 Set tst = 2 Get tst 2