How do I conditionally add a hash to an *args array in Rails? I don’t want to stomp on the original value if one exists.
For instance, I have an method that receives an array:
def foo(*args)
# I want to insert {style: 'bar'} into args but only if !style.present?
bar(*args) # do some other stuff
end
I’ve started using the extract_options and reverse_merge methods provided by rails:
def foo(*args)
options = args.extract_options! # remove the option hashes
options.reverse_merge! {style: 'bar'} # modify them
args << options # put them back into the array
bar(*args) # do some other stuff
end
It works but seems verbose and not very ruby-ish. I feel like I’ve missed something.
Yes,
#extract_options!is the way to do it in Rails. If you want to be more elegant, you’ll have to alias it, or find your own way of handling this need, or search for gem by someone who has already done it.