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.
In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).
We can merge two hashes using the merge() method. When using the merge() method: Each new entry is added to the end. Each duplicate-key entry's value overwrites the previous value.
Parameters should be defined before use of a method. Parameters are separated by a comma. Parentheses for parameter definition are optional. Parameters must be added to a method when the necessary data is inaccessible within the method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With