简体   繁体   中英

Replace “%20” with “-” in URL for rails

I'm developing a web application using rails. For aesthetic purposes, i need to replace %20 with -

Before: http://localhost:3000/movies/2006/Apna%20Sapna%20Money%20Money

After: http://localhost:3000/movies/2006/Apna-Sapna-Money-Money

Is there anyway i can achieve this in rails?

You should use URI.parse to break it into pieces and then change only the path component:

require 'uri'
u      = URI.parse(url)
u.path = u.path.gsub('%20', '-')
url    = u.to_s

Just a simple gsub on the whole URL would probably work fine but a little extra paranoia might save you some confusion and suffering down the road. Also, if you're just replacing a literal string rather than a regular expression, you can use a String as the first argument to gsub and avoid some escaping issues:

The pattern is typically a Regexp; if given as a String, any regular expression metacharacters it contains will be interpreted literally, eg '\\d' will match a backlash followed by d , instead of a digit.

If your string is stored in the variable url you can use

url.gsub(/%20/, "-")

to return the string you want, or

url.gsub!(/%20/, "-")

to actually modify the value of url with the value you want.

https://github.com/FriendlyId/friendly_id

this is the best way to go about seo urls

You probably want to be saving "Apna-Sapna-Money-Money" within your Movies model as an attribute (I usually call these slug s). Then, to generate these, you might just need to replace spaces in the movie title with hyphens. Something like:

class Movie
  before_create :generate_slug

  private
  def generate_slug
    slug = title.gsub(" ", "-")
  end
end

Then in your controller action you can simply do a Movie.find_by_slug:(params[:id]) call.

Basically, there should be no reason for users to ever arrive at a URL with %20 in it...

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM