Ariel Rodriguez Romero

Override-able options in rails partial view

Sometimes you have partial views with static values that would be nice to change, but adding specific options for each one of them would be painful.

A better approach is to have all these values in a hash, at the beginning of the partial view. And allow changing all of them with a parameter.

options = {
  styles: {
    main: stylesheet_url('external/styles'),
    list: stylesheet_url('external/list'),
    side: stylesheet_url('external/side'),
}.deep_merge((defined?(options) && options) || {})

	Use options here as usual...

	<p><%= options[:styles][:main] %></p>
	<p><%= options[:styles][:list] %></p>
	<p><%= options[:styles][:side] %></p>

This partial view can be rendered as usual, with the only difference that you can pass an additional object options and override each one of the values there.

<%= render 'partial_view_name', options: {styles: { main: stylesheet_url('other/main') }} %>

Note that you don’t need to pass all the parameters, just the ones you need to change. As both hashes are merged using deep merge.

Related posts

Hiding state, simplifying modal dialogs usages

Render props is a very powerful technique in React, here it’s applied to Modal Dialogs to simplify their usage. There’re examples with react-modal.

Problems with my laptop HP Envy 15t-as100

My laptop died suddenly after 19 months, I tried to fix it. This is the story.

Jekyll: Re-designing my personal blog.

Finally! I updated the blog. I talk about the entire process here.