ruby-on-rails - 在模型的属性中包含字符串插值

标签 ruby-on-rails ruby string postgresql model

我想创建一个带有包含字符串插值的字符串属性的 Active Record 对象。

我的模型架构如下所示:

  create_table "twilio_messages", force: true do |t|
    t.string   "name"
    t.string   "body"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

我使用 Active Admin 创建了这个模型的对象,如下所示:

  => #<TwilioMessage id: 5, name: "weekly_message", body: "\#{user.firstname} you're on the list for this week'...", created_at: "2014-05-29 22:24:36", updated_at: "2014-05-30 17:14:56"> 

问题是我为正文创建的字符串应该如下所示:

"#{user.firstname} you're on the list for this week's events! www.rsvip.biz/#events"

以便将 user.firstname 插入到字符串中,从而打印出用户名。

如何在数据库不自动尝试用“\”转义插值的情况下创建这种类型的记录?

最佳答案

你可以那样做,除非你想使用像 eval 这样讨厌的东西。字符串插值仅发生在字符串文字中,您不能说 s = '#{x}' (不是单引号)然后在需要时替换 x使用 s

String#%虽然:

str % arg → new_str

Format—Uses str as a format specification, and returns the result of applying it to arg. If the format specification contains more than one substitution, then arg must be an Array or Hash containing the values to be substituted. See Kernel::sprintf for details of the format string.

所以你可以像这样使用body:

m = TwilioMessage.create(
  :body => "%{firstname} you're on the list for this week's events! www.rsvip.biz/#events",
  ...
)

然后,当您有了用户时,像这样填写消息:

body = m.body % { :firstname => user.firstname }

当然,您必须知道 %{firstname} 在字符串中。如果您只有少量要插入的内容,那么您可以提供所有内容并让 % 挑选出需要的内容:

body = m.body % {
  :firstname => user.firstname,
  :lastname  => user.lastname,
  :email     => user.email
}

甚至为您的用户添加一个方法:

def msg_vals
  {
    :firstname => self.firstname,
    :lastname  => self.lastname,
    :email     => self.email
  }
end

然后说这样的话:

body = m.body % user.msg_vals

关于ruby-on-rails - 在模型的属性中包含字符串插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23960084/

相关文章:

ruby - 如何将 .rb 文件中的值渲染到 .erb 文件中

java - 逐个字符翻译字符串

python - 如何在 python 中替换字符串的一部分?

ruby-on-rails - Rails 3 的反馈 gem

ruby-on-rails - 当数据库在不同的服务器上时安装 postgres gem

ruby-on-rails - AngularJS/Rails 移动 session 仅持续一个小时

ruby-on-rails - 未定义的方法 `name' 为 "actionmailer":String

ruby - 拆分、重新排列和连接字符串

ruby-on-rails - capybara 不会等待 factory_girl 完成

C计算字符串中大小写字母的个数