1

I am new to Ruby and this is a really basic question, when I searched for adding/appending values to OpenStruct, I couldn't find any resource.

I'm trying to wrap the response body with extra params and the code in place uses OpenStruct. Now I need to append some key/value later in the code before sending the final reponse.

OpenStruct.new(
  body : api_response.body
  check1? : true
) 

I want to add check2? : false.

2 Answers2

2

The whole point of OpenStruct is that you can add new fields on the fly.

response = OpenStruct.new(
  body: 'foo',
  check1: true
)
response.check2 = false
p response
# => #<OpenStruct body="foo", check1=true, check2=false>

This is the only advantage that it has over Struct. Using OpenStruct incurs a considerable performance penalty, so if you don't need to add new fields later, it should never be used (unless of course you absolutely don't care about performance); use Struct instead.

However, specifically in your case, Ruby's parser does not allow methods of form check1?=, as both the question mark and the equality sign are only permitted at the end of the identifier; i.e. check1= is a valid method name, check1? is a valid method name, but check1?= is not.

tl;dr: Drop the question mark.

Amadan
  • 191,408
  • 23
  • 240
  • 301
0

There are two ways to do it depending on what works best for the use case. One can either do a quick fix with something like this

openstruct_object.check2? = false

OR an elegant way of doing it is to wrap the creation of your OpenStruct instance in a method that accepts the check2? param. (This is what I did and it works great with named args!)

def wrap_reponse(body, check1 = "your_default", check2: "named_args")
  OpenStruct.new(
    body : body,
    check1? : true,
    check2? : false
  )
end

There is a good blog for reference, which I got after considerable google search.