Search code examples
ruby-on-railsrubyregextagshashtag

Saving Twitter Like Hashtags with Regex Rails


Thanks for your help! I'm trying to save twitter like hashtags in my rails app. Users enter their tags prepended by the #hashtag symbol. However, it keeps saving empty strings. I added an additional unless statement to combat it, but now it doesn't save any tags. Code:

def tag_list=(names)
  self.tags = names.split(/\B#\w+/).map do |n|
    unless n.strip == "" || n.strip == nil
      Tag.where(name: n.strip).first_or_create!
    end
  end
end

I've also tried the following regex which also return the same:

/\B#\w+/

/(?:^|\s)(?:(?:#\d+?)|(#\w+?))\s/i

/(?:\s|^)(?:#(?!\d+(?:\s|$)))(\w+)(?=\s|$)/i

Solution

  • Your first regex works totally, but you must use scan instead of split, so your code to assign the tags would be:

    def tag_list=(names)
      self.tags = names.scan(/\B#\w+/).map do |tag|
        Tag.find_or_initialize_by(name: tag.remove('#'))
      end
      save!
    end
    

    The changes are:

    • Use scan
    • Use find_or_initialize_by instead of where then first_or_create!
    • Use save! at the end to save once
    • You may not need tag.remove('#') if you want to save the hashtag with # prefix