Ruttkowa
Ruttkowa

Reputation: 69

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. I have a Table with 20+ Columns and a corresponding XML File which can be parsed as some sort of hash with a gem. 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:

filename["crs","inputkeyhere"]

which returns the value, for example "52" or whatever.

What I am trying to do is upload the file, parse it with the gem and give each column the corresponding value.

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|
  3. Use the rails possibilty to set attributes by calling the corresponding @attributeset.
  4. Set colum attribute to the corresponding xml key

So my code would go something like this:

@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. I've read through lambdas and procs and whatnot but didn't really understand how they could work for my specific situation.

Coming from bash scripting maybe my thinking might be wrong but I thought that the .a might get evaluated. I know I can run the block with yield, but this only works in methods as far as I know..

Any help is appreciated. Thanks and stay healthy, Alex

Upvotes: 0

Views: 609

Answers (2)

3limin4t0r
3limin4t0r

Reputation: 21110

You can use []= method to set values dynamically:

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

Upvotes: 0

Ruttkowa
Ruttkowa

Reputation: 69

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.

Upvotes: 1

Related Questions