简体   繁体   English

在Rails插件中扩展核心类无法正常工作

[英]Extending a core class in rails plugin is not working

Inside of #PLUGIN/lib/#PLUGIN I inserted the following: #PLUGIN/lib/#PLUGIN内部,我插入了以下内容:

String.class_eval do
  def to_squawk
    "squawk! #{self}".strip
  end
end

And when I try to test in Rails Console. 当我尝试在Rails Console中进行测试时。 I get the following error: NoMethodError: undefined method to_squawk' for "test string":String` 我收到以下错误: NoMethodError: undefined method “测试字符串”的NoMethodError: undefined method to_squawk':String`

Loading development environment (Rails 4.2.0.beta2)
2.1.3 :001 > "test string".to_squawk
NoMethodError: undefined method `to_squawk' for "test string":String
  from (irb):1
  from /Users/fab/.rvm/gems/ruby-2.1.3/gems/railties-4.2.0.beta2/lib/rails/commands/console.rb:110:in `start'
  from /Users/fab/.rvm/gems/ruby-2.1.3/gems/railties-4.2.0.beta2/lib/rails/commands/console.rb:9:in `start'
  from /Users/fab/.rvm/gems/ruby-2.1.3/gems/railties-4.2.0.beta2/lib/rails/commands/commands_tasks.rb:68:in `console'
  from /Users/fab/.rvm/gems/ruby-2.1.3/gems/railties-4.2.0.beta2/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
  from /Users/fab/.rvm/gems/ruby-2.1.3/gems/railties-4.2.0.beta2/lib/rails/commands.rb:17:in `<top (required)>'
  from bin/rails:4:in `require'
  from bin/rails:4:in `<main>'

I am following the tutorial here: http://guides.rubyonrails.org/plugins.html 我在这里关注该教程: http : //guides.rubyonrails.org/plugins.html

Does anyone know what the problem is here? 有人知道这是什么问题吗?

This is the code in the Rails Guide: 这是Rails指南中的代码:

String.class_eval do
  def to_squawk
    "squawk! #{self}".strip
  end
end

This is your code: 这是您的代码:

String.class_eval do
  def self.to_squawk
    "squawk! #{self}".strip
  end
end

See the difference? 看到不同? The Guide's code defines an instance method that instances of String respond to (ie "foo".to_squawk # => "squawk! foo" ), but your code with its stray self defines a class method that the String class responds to (ie String.to_squawk # => "squawk! String" ). 指南的代码定义了String实例响应的实例方法(即"foo".to_squawk # => "squawk! foo" ),但是您的代码及其杂散的self定义了String类响应的类方法(即String.to_squawk # => "squawk! String" )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM