While I was implementing the home dashboard widgets with Gridster, I needed to ajax load the contents of each widget base on the widget key. The Gridster widget keys are string based, however some keys are dynamically generated.
Let’s look at an example.
The simple case first. A widget key can be
my_calendar. I need ruby to translate it to a symbol such as
:my_calendar. I’ll then be able to utilise the translated value
:my_calendar to fetch the widget content. To achieve this, it’s dead simple … A contrive way to do it can be somethign like this
Now let’s go to the deep end. Many widgets have dynamically generated keys like
my_type_456. I need to extract out
:my_type, as well as the integers (sort of like type IDs) such as
So … let’s see if we can implement a Hash-alike data structure that allows us to fetch values by passing in strings that can be recognised by a Regex.
With the above in place, I can use the
DYNAMIC_WIDGET_KEY_SPLIT_MAP constant as if it’s just a regular Hash object. The translated return values can be used to call up named URLs defined in my
routes.rb and have the ability to pass in those additional params.
I don’t know if anybody would have a similar use case to use this implementation. However it solved my problem quite nicely.