0

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

1
  • 3
    can you try with @attributeset.public_send("#{a}=", filename["crs",a])? with public_send you can call methods from the object passing arguments to it Commented Apr 12, 2020 at 20:35

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.