[RUBY] A collection of methods that replace characters entered in hashtag search with a nice feeling

Introduction

Thing you want to do

--I want to convert the full-width hash entered in the hashtag search to half-width. ――I want to make full-width numbers half-width ――I want to remove the hash and search in the first place

Reason to do

――I want to replace the output with a feeling that the user can input in any way

Method

--tr method --delete method

tr method

Method to convert the first argument to the second argument

sample.rb


str = 'Ichiro'
puts str.tr('one', 'two')

#result=>Jiro

Add this to the search action defined in the model

Default search action

models/hashtag.rb


def self.search(search)
  if search != ""
    Hashtag.where('name LIKE(?)', "%#{search}%")
  else
    Hashtag.all
  end
end

search action with tr method added

models/hashtag.rb


def self.search(search)
  if search != ""
    Hashtag.where('name LIKE(?)', "%#{search.tr('#', '#').tr('/0-9/', '/0-9/')}%")
  else
    Hashtag.all   
  end
end

Replaced # and numbers entered in full-width with half-width.

delete method

When searching in the form without the hash

models/hashtag.rb


def self.search(search)
  if search != ""
    Hashtag.where('name LIKE(?)', "%#{search.tr('#', '#').tr('/0-9/', '/0-9/').delete('#')}%")
    Hashtag.all   
  end
end

in conclusion

I didn't like the fact that half-width numbers and full-width numbers were mixed up in the hashtag, so I validated the full-width numbers when entering the hashtag. (I really wanted to replace it and save it, but I didn't know how to do it and gave up)

For the time being, I'm glad that this method will pick up the search user as if he / she can enter any keyword.

✔︎

Recommended Posts

A collection of methods that replace characters entered in hashtag search with a nice feeling
A collection of phrases that impresses the "different feeling" of Java and JavaScript
A collection of methods often used when manipulating time with TimeWithZone of Rails
It's just now, but a collection of commands that frequently appear in Rails
A collection of RSpecs that I used frequently