metaprogramming - result of 'self' in ruby module -
module cnblog2jekyll class << self attr_accessor :username [:archive_links, :article_links].each |method_name| define_method method_name instance_value = instance_variable_get(("@" + method_name.to_s).to_sym) instance_value ? instance_value : send("get_" + method_name.to_s) # @archive_links ? @archive_links : get_archive_links end end binding.pry def test binding.pry end end end
please ignore meaning of part code , mind place of 'binding.pry'.
here comes question: type in 'self' in pry console @ place of 'binding.pry', , give result:
from: /home/yanying/cnblog2jekyll/lib/cnblog2jekyll.rb @ line 20 : 15: instance_value = instance_variable_get(("@" + method_name.to_s).to_sym) 16: instance_value ? instance_value : send("get_" + method_name.to_s) 17: # @archive_links ? @archive_links : get_archive_links 18: end 19: end => 20: binding.pry 21: 22: def test 23: binding.pry 24: end 25: [1] pry(#<class>)> self => #<class:cnblog2jekyll> [2] pry(#<class>)> self.class => class [3] pry(#<class>)> self.ancestors => [#<class:cnblog2jekyll>, module, object, pp::objectmixin, kernel, basicobject] [4] pry(#<class>)> => true [2] pry(main)> cnblog2jekyll.test from: /home/yanying/cnblog2jekyll/lib/cnblog2jekyll.rb @ line 23 cnblog2jekyll.test: 22: def test => 23: binding.pry 24: end [1] pry(cnblog2jekyll)> self => cnblog2jekyll [2] pry(cnblog2jekyll)> self.class => module [3] pry(cnblog2jekyll)> self.ancestors => [cnblog2jekyll] [4] pry(cnblog2jekyll)>
so, question is: why first result of 'self' 'class'? second of "module"? what's magic here?
since using class << self
, open self
singleton class, , methods inside redefine methods of current self
, in case module cnblog2jekyll
if had:
class cnblog2jekyll def foo end class << self def bar end end end
and called cnblog2jekyll.new.bar
undefined_method
, because bar specified class method, not object method. in case, methods module
methods, because class << self
inside module block.
check out this question class << self
idiom , this article it.
Comments
Post a Comment