Inside of #PLUGIN/lib/#PLUGIN
I inserted the following:
String.class_eval do
def to_squawk
"squawk! #{self}".strip
end
end
And when I try to test in Rails Console. I get the following error: NoMethodError: undefined method
to_squawk' for "test string":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
Does anyone know what the problem is here?
This is the code in the Rails Guide:
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"
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.