james james - 6 months ago 18
Ruby Question

Function Parameters to Hash Symbols for Rendering Partials

I have a lot of Render Helper functions like

def generic_form_datetime_field(f,attribute_name, my_label ,selected_model_instance)
render(:partial => 'common_partials/generic_form/datetime_field',
:locals => {:f => f,
:attribute_name => attribute_name,
:my_label => my_label,
:selected_model_instance => selected_model_instance

notice the local field is full of duplicate keys and values from function parameters. What is the best practice around this? Is there a way to get the parameters from the method and put them as keys for the hash?

Del Del

taking hash arguments

You can use a few different syntaxes to pull in named arguments as a hash. One is using the "double splat":

def func(**args)
  puts args

func(a: 'aval', b: 3)  # prints {:a=>"aval", :b=>3}

Another syntax you will see is:

def func(opts={})
  puts opts

func(a: 'aval', b: 3)  # prints: {:a=>"aval", :b=>3}

More info can be found in this blog post.

filtering the hash

If you want to be defensive, you can use a function that filters collections in general: select. Here's an example of how to only take values from a specified whitelist for hash keys:

h = {a: 'a', b: 'b', c: 'c'}
whitelist = [:a, :c]
h.select { |k, _| whitelist.include?(k) }  
# result: {:a=>"a", :c=>"c"}