Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

ruby on rails - `Case/when` statement works some of the time

Ok I am creating a gem that is supposed to find tags #, @, or $ in user's posts. I am using a case when statement and it seems to work, only sometimes. For example I will have a string like @you and that works, but #cool does not work unless I add #cool @you. It seems the other when statements only work if the first when statement is true. The REGEX is just so it knows what to look for and I know those do work.

  REGEXS = [Supertag::Tag::USERTAG_REGEX, Supertag::Tag::HASHTAG_REGEX, Supertag::Tag::MONEYTAG_REGEX]

  def linkify_tags(taggable_content)
    text = taggable_content.to_s

    REGEXS.each do
      case text
      when text = text.gsub(Supertag::Tag::USERTAG_REGEX) {link_to($&, usertag_path($2), class: 'tag')}
      when text = text.gsub(Supertag::Tag::HASHTAG_REGEX) {link_to($&, hashtag_path($2), class: 'tag')}
      when text = text.gsub(Supertag::Tag::MONEYTAG_REGEX) {link_to($&, moneytag_path($2), class: 'tag')}
      end  
    end     

    text.html_safe
  end
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For some reason you iterate over REGEXS, ignore the item in the iteration, then hard-code them again... you actually do text.gsub(Supertag::Tag::USERTAG_REGEX) ... 3 times - once for each REGEX in your list.

Also, you misuse the case when construct, I suggest you read more about it

You should either drop the each entirely, and use only the explicit constants, or refactor you code to work dynamically, maybe something like:

  REGEXS = [[Supertag::Tag::USERTAG_REGEX, :usertag_path], 
            [Supertag::Tag::HASHTAG_REGEX, :hashtag_path], 
            [Supertag::Tag::MONEYTAG_REGEX, :moneytag_path]]

  def linkify_tags(taggable_content)
    text = taggable_content.to_s

    REGEXS.each do |regex, path|
      text = text.gsub(regex) {link_to($&, send(path, $2), class: 'tag')}
    end     

    text.html_safe
  end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...