简体   繁体   English

如何将字符串插值代码传递到Rails应用模板代码块?

[英]How to pass string interpolation code to Rails Application Template CODE block?

According to Rails Application Templates this is how one can write ruby code into the file: 根据Rails应用程序模板,这是将红宝石代码写入文件的方式:

file 'path/to/my_file.rb', <<-CODE
  class Object
    def not_nil?
      !nil?
    end

    def not_blank?
      !blank?
    end
  end
CODE

However when I try to add code containing string interpolation between <<-CODE and CODE , it fails on its first occurrence. 但是,当我尝试添加在<<-CODECODE之间包含字符串插值的CODE ,它在第一次出现时失败。

My file call: 我的file呼叫:

file 'lib/person.rb', <<-CODE
# frozen_string_literal: true

class Person
  def initialize(first_name, last_name)
    @full_name = "#{first_name.capitalize} #{last_name.capitalize}#"
  end
end
CODE

Error message: 错误信息:

template.rb:50:in apply : undefined local variable or method first_name for Rails::Generators::AppGenerator:0x00005557a8d85090 (NameError) template.rb:50:in apply :Rails :: Generators :: AppGenerator:0x00005557a8d85090的未定义局部变量或方法first_name (NameError)

My understanding is that the template generator tries to execute the interpolated code. 我的理解是模板生成器尝试执行内插的代码。

What I tried was simply escaping the " double quotes, like: 我试过的只是将"双引号"转义,例如:

file 'lib/person.rb', <<-CODE
# frozen_string_literal: true

class Person
  def initialize(first_name, last_name)
    @full_name = \"#{first_name.capitalize} #{last_name.capitalize}#\"
  end
end
CODE

but it did not help, resulting in exactly the same error. 但它没有帮助,导致完全相同的错误。

How can I approach this? 我该如何处理?

You are trying to use heredoc with string interpolation, which obviously fails on the attempt to interpolate first_name . 您正在尝试将Heredoc 字符串插值一起使用,显然在尝试插值first_name失败。 To prevent the heredoc string interpolation, use FOO<<-'CODE' instead: 为防止heredoc字符串插值,请改用FOO<<-'CODE'

file 'lib/person.rb', <<-'CODE'
# frozen_string_literal: true

class Person
  def initialize(first_name, last_name)
    @full_name = "#{first_name.capitalize} #{last_name.capitalize}#"
  end
end
CODE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM