0

I want to link to /member/:name. I'm using this line in routes.rb:

match 'member/:id', :to => "members#show", :as => :show_member, :via => :get

and this in the model:

def to_param
  username
end

Next, I want to link to a the name represented as a string that has white spaces. I want to replace the white spaces with + (plus) or something else more readable than standard %20 replacement.

I could handle these replacements (from space to +, and from + to space) in a method, but I was wondering if there is a better way of handling this.

sawa
  • 165,429
  • 45
  • 277
  • 381
Marcus Brunsten
  • 575
  • 5
  • 22

3 Answers3

3

@screenmutt is right of course. However, have you tried returning the desired string from to_param? I'm unsure whether it would URL encode the +, but my instinct is that it wouldn't because it's a valid URL character.

def to_param
  username.tr(' ', '+')
end

Then you'd need to write a finder method that converts the + back to a space..

def self.from_param(uname)
  find_by_username!(uname.tr('+', ' '))
end
Mike Campbell
  • 7,921
  • 2
  • 38
  • 51
  • Thank you, this seems about right on what i want to do. I want to use the plus-sign instead of html-space. (its more pretty :-) ) – Marcus Brunsten Nov 22 '13 at 15:09
1

You might want to check out the friendly_id gem which was created for this purpose. If you would like to create it yourself then I would consider adding an attribute to the database to store the value by which you will lookup the user. As an idea...

class User < ActiveRecord::Base
  after_create :build_url_parameter
  validates_uniqueness_of :url_parameter, :on => :update

  def to_param
    self.url_parameter
  end

  private
    def build_url_parameter
      self.url_parameter = self.name.gsub(/\s+/, '-')
      unless User.where( url_parameter: self.url_parameter ).count.zero?
        self.url_parameter << "-#{self.id}"
      end
      save
    end
end

By taking this approach you guarantee that the parameter is unique (which may not otherwise be true of users' names).

AndyV
  • 3,696
  • 1
  • 19
  • 17
0

Marcus,

This is not something which is standard. Browsers will write %20 for spaces inside of the URL and + for spaces inside of queries.

The only way to convert this would be to do a redirect every time the user searches for a URL with a %20 in it.

However, I don't think this would be worth the effort. Why violate a standard?

When to encode space to plus (+) or %20?

Community
  • 1
  • 1
Dan Grahn
  • 9,044
  • 4
  • 37
  • 74