开发者

Can`t remove a new line

开发者 https://www.devze.com 2023-03-30 09:09 出处:网络
I have a model, wich has a unique token, to be changed every time the model is saved. i`m using before_filter to change the token, and it is working, the problem is:

I have a model, wich has a unique token, to be changed every time the model is saved.

i`m using before_filter to change the token, and it is working, the problem is:

class Confirmation < ActiveRecord::Base
  attr_accessible :item_id, :item_type

  before_save :define_token

  def to_param
    token
  end

  private
    def define_token
      str = ActiveSupport::SecureRandom.base64(32).gsub("/","_").gsub(/=+$/,"")
      self.token = Util.secure_hash("#{str} - #{Time.now.utc.to_s} - #{item_id}")
    end
end

when i look the token generated it gives me a random string with a \n at th开发者_JS百科e end.

i`ve tried to add this line:

def define_token
  str = ActiveSupport::SecureRandom.base64(32).gsub("/","_").gsub(/=+$/,"")
  str = Util.secure_hash("#{str} - #{Time.now.utc.to_s} - #{item_id}")
  self.token = str.gsub("\n", "n")
end

but still don`t work, how can i remove the new line at the end?


Firstly, assuming the newline is 100% spurious, I would figure out where it is coming from, and remove it there. But if for some reason that's not an option, the following gsub would work:

self.token = str.gsub(/\n$/, "")

That will only remove a newline if it's the last entry in the string. To remove all newlines, use:

self.token = str.gsub(/\n/, "")

Even easier, the rstrip method will remove trailing whitespace from a string:

self.token = str.rstrip
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号