Archer
Archer

Reputation: 1124

Return content of named parameter in rails

I've created a helper to return an array, depending on the param.

self.modules(package)
  package1 = [:mod1, :mod2, :mod5]
  package2 = [:mod3, :mod9, :mod10]
  package3 = [:mod4, :mod6, :mod7, :mod8, :mod7]
  all = package1 + package2 + package3

  return package1 if package == 'package1'
  return package2 if package == 'package2'
  return package3 if package == 'package3'
  return all if package == 'all'
end

Is there a posibility in rails to say just

return package

I've tried package.to_sym, but it doesn't work.

Upvotes: 1

Views: 32

Answers (2)

Slava.K
Slava.K

Reputation: 3080

One way to do what you want is to combine your options to a hash:

self.modules(package)
  packages = {
    package1: [:mod1, :mod2, :mod5],
    package2: [:mod3, :mod9, :mod10],
    package3: [:mod4, :mod6, :mod7, :mod8, :mod7]
  }
  packages[:all] = packages.values.flatten

  return packages[package.to_sym]
end

This will also allow you to avoid metaprogramming (having said this I do not mean that metaprogramming is bad, but IMO it is just unnecessary in the given case)

Upvotes: 2

Ursus
Ursus

Reputation: 30056

Try

self.modules(package)
  package1 = [:mod1, :mod2, :mod5]
  package2 = [:mod3, :mod9, :mod10]
  package3 = [:mod4, :mod6, :mod7, :mod8, :mod7]
  all = package1 + package2 + package3

  binding.local_variable_get(package)
end

Upvotes: 2

Related Questions