简体   繁体   English

Rails 上的 Ruby - 使用块参数作为方法调用

[英]Ruby on Rails - using a block parameter as a method call

I'm having trouble with a little Ruby on Rails I'm building and need some help.我在我正在构建的 Rails 上遇到一点 Ruby 的问题,需要一些帮助。 I have a Table with 20+ Columns and a corresponding XML File which can be parsed as some sort of hash with a gem.我有一个包含 20 多列的表和一个相应的 XML 文件,可以将其解析为某种带有 gem 的 hash。 Every key would be mapped to a column and every value would be a data record in said column.每个键都将映射到一列,每个值将是所述列中的数据记录。

The way I access a specific value in the already parsed XML file is:我在已解析的 XML 文件中访问特定值的方式是:

filename["crs","inputkeyhere"]

which returns the value, for example "52" or whatever.它返回值,例如“52”或其他。

What I am trying to do is upload the file, parse it with the gem and give each column the corresponding value.我要做的是上传文件,用 gem 解析它并为每一列赋予相应的值。

My table (or model) is called "Attributeset" and I already know how I can access every column:我的表(或模型)被称为“属性集”,我已经知道如何访问每一列:

@attributeset = Attributeset.new    
@attributeset.attributes.keys

So my thought process was:所以我的思考过程是:

  1. Iterate over all the keys遍历所有键
  2. Pass every key into a block called |a|将每个键传递到一个名为 |a| 的块中
  3. Use the rails possibilty to set attributes by calling the corresponding @attributeset.通过调用相应的@attributeset 使用rails possibilty 设置属性。
  4. Set colum attribute to the corresponding xml key将colum属性设置为对应的xml键

So my code would go something like this:所以我的代码将 go 是这样的:

@attributeset.attributes.keys.each do |a|
      @attributeset.a=filename["crs",a]
 end

But my problem is, that ruby thinks ".a" is a method and apparently does not evaluate "a" to the block parameter.但我的问题是,ruby 认为“.a”是一种方法,显然不会对块参数评估“a”。 I've read through lambdas and procs and whatnot but didn't really understand how they could work for my specific situation.我已经阅读了 lambdas 和 procs 之类的东西,但并没有真正理解它们如何适用于我的具体情况。

Coming from bash scripting maybe my thinking might be wrong but I thought that the.a might get evaluated.来自 bash 脚本可能我的想法可能是错误的,但我认为 the.a 可能会被评估。 I know I can run the block with yield, but this only works in methods as far as I know..我知道我可以使用 yield 运行该块,但这仅适用于我所知道的方法。

Any help is appreciated.任何帮助表示赞赏。 Thanks and stay healthy, Alex谢谢,保持健康,亚历克斯

Thanks for the input, I wanted to make it as clean as possible.感谢您的输入,我想让它尽可能干净。 and not using any temporary hashes to pass arguments.并且不使用任何临时哈希来传递参数。 I've found the method我找到了方法

write_attribute

which can be used like this:可以这样使用:

  @attributeset.write_attribute(a, xmp["crs",a])

worked perfectly for me.非常适合我。

You can use []= method to set values dynamically:您可以使用[]=方法动态设置值:

@attributeset.attribute_names.each do |attribute|
  @attributeset[attribute] = filename["crs", attribute]
end

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

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