Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method For Making Methods: Easy Ruby Metaprogramming

I have a bunch of methods like this in view helper

  def background
    "#e9eaec"
  end
  def footer_link_color
    "#836448"
  end

I'd like these methods exposed to the view, but I'd prefer the helper to be a bit more concise. What's the best way to turn a hash, say, into methods (or something else)?

like image 762
Dan Rosenstark Avatar asked Feb 28 '23 00:02

Dan Rosenstark


1 Answers

module MyHelper
  {:background => "#e9eaec", :footer_link_color => "#836448"}.each do |k,v|
    define_method(k) {v}
  end
end

Though I don't think trading this bit of conciseness for the readability of your first approach is necessarily a good idea.

If you want to generalize this, you can add the following method to the Module class:

class Module
  def methods_from_hash(hash)
    hash.each do |k,v|
      define_method(k) {v}
    end
  end
end

And then in your helper call methods_from_hash(:background => ...).

like image 144
sepp2k Avatar answered Mar 12 '23 04:03

sepp2k