Topic: Please help me DRY up my controller

Hi,

in my controller code I have plenty of constructions like these:

  GENDER = [
    [ "Male",   "m" ],
    [ "Female", "f" ]
  ].freeze
 
  def full_gender
    GENDER.detect { |g| g.last == gender }.first
  end   
 
  COUNTRY = [
    [ "Germany",  "de" ],
    [ "France",   "fr" ],
    [ "Italy",    "it" ],
    [ "Sweden",   "se" ]
  ].freeze
 
  def full_country
    COUNTRY.detect { |g| g.last == country }.first
  end

As you can see each array CONSTANT also has a correspoding method full_CONSTANT which is needed for displaying a proper select list in my views. I just wonder if I can somehow reduce the amount of repitition that is involved here... Can anybody help me out here?

Last edited by Pixelateur (2007-05-13 14:33:53)

Re: Please help me DRY up my controller

Your constants really should be stuck in a model class, they don't belong in a controller.

To solve your problem just stick these things in a Hash instead of an array. Then you access the full gender via the hash key.

GENDER = { 'm' => 'Male', 'f' => 'Female' }

To fetch a 'full gender' just access the hash:
GENDER['m']

will display the full gender.

And remember, put it all inside a model class. Doesn't have to be an ActiveRecord class, but must reside in the models directory.

email the future with www.l8r.nu

Re: Please help me DRY up my controller

Not sure but I think it's not necessary to freeze any constant content.
If you don't switch to a hash, the following array methods could me interesting:

a = [[1, "one"], [2, "two"]]

puts a.rassoc("one").first.to_s  # "1"
puts a.assoc(1).last             # "one"
puts a.assoc(2).last             # "two"
# ...

# rassoc and assoc

Last edited by joern (2007-05-14 05:11:57)

Re: Please help me DRY up my controller

OK, this is embarassing, but the code I posted above is in fact in my Model, and not in my Controller... I am using an array because I can easily use it in my views too:

<%= @promoter.full_gender %>

With a hash this is more troublesome, no?

But you're right, the freeze statement is not really required here. I will just drop it...

Re: Please help me DRY up my controller

hi,

agreed with joost.

a hash would look like this:

 
  GENDER = { "m" => "Male", "f" => "Female" }

and your method should look like this:
  def full_gender
    GENDER[gender]
  end

greetz

Re: Please help me DRY up my controller

accessibilty of vars does not depend on the kind of class you are using.