rails环境下 ruby环境下class_eval的区别

rails环境下 ruby环境下class_eval的区别

先入为主,先看两段代码

1、写一段纯ruby脚本pure_ruby.rb:

module Big
  def middle(tiny)
    class_eval <<-RUBY_EVAL
      def #{tiny}
        "#{tiny}"
      end
    RUBY_EVAL
  end
end

class Size
  include Big

  def little
    middle("tiny")
  end
end

p Size.new.little       #=>class_eval undefine
p Size.instance_methods #=>[:little, :middle, ...]
p Big.instance_methods  #=>[:middle]

2、在rails环境下,比如/lib/rails_ruby.rake

desc 'the environment of ruby on rails'
task :rails_ruby, :enviroment => do
  module Big
    def middle(tiny)
      class_eval <<-RUBY_EVAL
        def #{tiny}
          "#{tiny}"
        end
      RUBY_EVAL
    end
  end

  class Size
    include Big

    def little
      middle("tiny")
    end
  end
end
p Size.new.little       #=>:little
p Size.instance_methods #=>[:little, :middle, :tiny, ...]
p Big.instance_methods  #=>[:middle, :tiny]

很显然,从Size.new.little的结果可以看出,include Big后,传到middleclass_evalself不是Size而是Size实例,而调用class_eval一定是Class或是Module,在rails环境下实例可以调用class_eval,这明显是rails框架的问题,通过pry的跟踪rails源码,原来是rails的activesupportKernelcalss_eval的重新定义,rails下calss_eval的源码

posted @ 2017-02-27 15:53  chzhzh  阅读(268)  评论(0编辑  收藏  举报