使用 Mandrill 时的 Ruby 引号语法

Posted

技术标签:

【中文标题】使用 Mandrill 时的 Ruby 引号语法【英文标题】:Ruby Quotes Syntax when using Mandrill 【发布时间】:2015-06-02 10:32:15 【问题描述】:

我有一个 Ruby on Rails 应用程序,我正在编写我的邮件程序以将 SMTP 标头发送到 Mandrill。 我想我在将变量放入字符串时遇到问题:

class MyMailer < Devise::Mailer

helper :application # gives access to all helpers defined within `application_helper`.
include Devise::Controllers::UrlHelpers # Optional. eg. `confirmation_url`

def confirmation_instructions(record, token, opts=)

     headers['X-MC-MergeVars'] = '"ctoken1": "Drip Email"'

     temp_var = "Hello Everyone"
     headers['X-MC-MergeVars'] = '"tag_test_1": "yoyoyo"'           # 1

    # headers['X-MC-MergeVars'] = "'tag_test_1': 'yoyoyo'"          # 2
    # headers['X-MC-MergeVars'] = "'tag_test_1': #temp_var"       # 3
    #  headers['X-MC-MergeVars'] = '"tag_test_1": #temp_var'      # 4

     headers['X-MC-MergeVars'] = '"ctoken3": "Test at the End"'

     super

end

end

我想将“temp_var”变量放入标题中。你可以看到我的 4 次尝试。

首先 - 健全性检查 - #1 中的语法工作正常 - 我的 mandrill 电子邮件中的变量“tag_test_1”被替换为“yoyoyo”,但当然这不是使用 ruby​​ 变量。

我的尝试 2,3 或 4 均无效。我的 Mandrill 电子邮件收到 TAG_TEST_1 而不是变量替换(“大家好”)。

我最终要做的是通过 Mandrill 将帐户激活链接放入电子邮件中。所以我想我需要发送“令牌”变量,但现在我似乎无法获得一个已知变量 (temp_var) 来传递给电子邮件。

我怀疑我没有正确理解 Ruby 字符串语法。

任何帮助表示赞赏!

【问题讨论】:

【参考方案1】:

我会试试这个:

headers['X-MC-MergeVars'] = "\"tag_test_1\": \"#temp_var\""

或者这个:

headers['X-MC-MergeVars'] = %Q'"tag_test_1": "#temp_var"'

【讨论】:

出色的 spickermann - 响应速度快得离谱!非常感谢 - 这非常有效。我想我需要转义引号字符 - 我无法完全理解我为什么需要它,但我现在可以继续。【参考方案2】:

首先,请务必注意,您不能在单引号内使用 # 语法。您只能在双引号内使用它。另请注意,当您使用新的哈希语法'': '' 时,它会将字符串转换为符号。上面的答案应该有效。

【讨论】:

以上是关于使用 Mandrill 时的 Ruby 引号语法的主要内容,如果未能解决你的问题,请参考以下文章

在 mandrill 模板中使用 Ruby/rails 变量

ruby 中的 Mandrill 验证,在 php 和 ruby​​ 之间的翻译中丢失

将 Mailchimp/Mandrill 与 Ruby 结合使用

Mandrill 在 Rails 上发送电子邮件 ruby

使用 ruby​​、Sinatra 和 Mandrill 如何从 api 调用访问单个元素并打印为 HTML?

找不到 Mandrill 红宝石宝石的方法 - 示例中的剪切和粘贴