在这种情况下我如何避免 eval [英] how can i avoid eval in this situation

查看:97
本文介绍了在这种情况下我如何避免 eval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

写一个title_tag helper,我想有如下yml文件结构

Writing a title_tag helper, i want to have the following yml file structure

index: Hello {{@game.name}}
edit: Edit {{@game.name}} - {{@game.classification}}

到那时我会使用 I18n 翻译字符串并需要用实际上下文替换 {{var}}.

by then i take the I18n translation string and need to replace {{var}} with actual context.

title = I18n.t "title_tags.#{namespace}.#{controller_name}.#{action_name}", default: ""

title.scan(/\{\{.*?\}\}/).each do |replace|
  # transform {{@game.name}} => @game.name
  var = replace.gsub(/\{|\}/, "")
  title.gsub! replace, eval(var)
end      

这很有效.另一方面,用户可能会上传一些名为system(rm -rf/*)"的游戏,这可能会给我们带来一些真正的危险?

this is working pretty sweet. on the other side, there is a possibility that a user might upload some game with a name "system(rm -rf /*)" which might cause some real danger for us ?

是否有可能以更安全的方式运行它?

are there any possibilities to get this running in a safer way?

多亏了 Axel 我可以用这些很酷的东西结束

Thanks to Axel i could end with this cool stuff

 title.scan(/\{\{.*?\}\}/).each do |replace|
    var = replace.gsub(/\{|\}/, "")                        

    # catch "resource" (like resource-controller)
    if var.starts_with? "resource"
      @tempresource = resource
      var.gsub!("resource", "@tempresource")
    end

    # @game or @game.name
    if var.starts_with?("@")          
      content = var.split('.').inject(nil){|clazz, method| clazz.nil? ? instance_variable_get(method) : clazz.send(method)}
      title.gsub! replace, content
    end
  end

工作出色!

推荐答案

您可以使用 send 代替 eval:

You can use send instead of eval:

content = var.split('.').inject(nil){|clazz, method| clazz.nil? ? instance_variable_get(method) : clazz.send(method)}
title.gsub! replace, content

这篇关于在这种情况下我如何避免 eval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆