开发者

Extending the "String" Class in Rails 2.x

开发者 https://www.devze.com 2023-02-19 19:08 出处:网络
I\'m writing an extension to the String class as such: #/lib/string.rb Class String def linkme return self.gsub(\"[/link]\", \"</a>\").gsub(\"[link=\", \"<a href=\'\").gsub(\"]\", \"\' targe

I'm writing an extension to the String class as such:

#/lib/string.rb
Class String
   def linkme
     return self.gsub("[/link]", "</a>").gsub("[link=", "<a href='").gsub("]", "' target='_new'>")
   end
end

When I call it in the console, however, I get this:

>>require 'lib/string'
SyntaxError: ./lib/string.rb:5: syntax error, unexpected kEND, expecting $end
   开发者_如何学JAVA from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
    from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
    from /home/path/to/vendor/rails/activesupport/lib/active_support/dependencies.rb:153:in `require'
    from /home/path/to/vendor/rails/activesupport/lib/active_support/dependencies.rb:521:in `new_constants_in'
    from /home/path/to/vendor/rails/activesupport/lib/active_support/dependencies.rb:153:in `require'
    from (irb):11

I figured this should work in theory, as I don't have any...

<geek_humor> loose "end"s </geek_humor>

This is my first attempt at really trying to extend a class like this in Ruby, and I thought I was doing pretty well, but maybe the S/O community can help me wrap it up.


This will work for you

class String
  def linkme
    self.gsub("[/link]", "</a>").gsub("[link=", "<a href='").gsub("]", "' target='_new'>")
  end
end
0

精彩评论

暂无评论...
验证码 换一张
取 消