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)?
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 => ...)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With