开发者

Ruby on Rails: reverse lookup of array list of values

i have a model with a user selectable option that is set up in an array on the model.

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

while the short string is retrieved from elsewhere and stored in the database, i would like to display the longer string when showing the object. e.g. in the view use:

Pie.display_customeor_choice[@pie_flavor]

i don't want to hard code the reverse hash, but if i create a display_options method that converts the array to a hash w开发者_开发知识库ith reverse mapping will it run the conversion every time display_options is called? this could be resource intensive with large arrays that are converted a lot, is there a way to create the reverse hash once when the app is started and never again? (using rails 3 and ruby 1.9.2)


You are looking for Array#rassoc

Pie.display_customeor_choice.rassoc("@pie_flavor")


Here's 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 guarantees it's going to be loaded only once on production (or other environments where cache_classes is set to true) but always reloads on development mode, making it simpler for you to change and see the changes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜