无法删除新行
我有一个模型,它有一个唯一的令牌,每次保存模型时都会更改。
我正在使用 before_filter 来更改令牌,并且它正在工作,问题是:
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
当我查看生成的令牌时,它给了我一个末尾带有 \n 的随机字符串。
我尝试添加这一行:
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
但仍然不起作用,我如何删除最后的新行?
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 the 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,假设换行符 100% 是假的,我会找出它来自哪里,并将其从那里删除。但是,如果由于某种原因这不是一个选项,则以下 gsub 可以工作:
如果换行符是字符串中的最后一个条目,则只会删除换行符。要删除所有换行符,请使用:
更简单的是, rstrip 方法将删除字符串尾随空格:
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:
That will only remove a newline if it's the last entry in the string. To remove all newlines, use:
Even easier, the rstrip method will remove trailing whitespace from a string: