Ruby on Rails: Reverse Lookup Array of List of Values

I have a user selectable model that is configured in the model array.

def Pie < ActiveRecored::Base def self.sel_options [ [ "Apple Blueberry", "AB" ], [ "Cranberry Date", "CD" ] ] end end 

while the short string is retrieved from other sources and stored in the database, I would like to display a longer string when showing the object. for example in a view use:

 Pie.display_customeor_choice[@pie_flavor] 

I don’t want to hard code the inverse hash, but if I create a display_options method that converts the array to a hash with the inverse mapping, will it trigger the conversion every time display_options is called? it can be resource intensive with large arrays that convert a lot, is there a way to create a reverse hash once when the application is launched and never again? (using rails 3 and ruby ​​1.9.2)

+4
source share
2 answers

Are you looking for Array # rassoc

 Pie.display_customeor_choice.rassoc("@pie_flavor") 
+4
source

Here is how you could do it:

 def Pie < ActiveRecored::Base def self.sel_options [ [ "Apple Blueberry", "AB" ], [ "Cranberry Date", "CD" ] ] end def self.display_customeor_choice unless @options @options = {} sel_options.each { |items| @options[items.last] = items.first } end @options end end 

This ensures that it will only be loaded once during production (or to other environments where cache_classes is set to true), but always reloaded in design mode, making it easy to change and view changes.

0
source

All Articles