ruby on rails - Pass a symbol to a method and call the corresponding method -


in rails controller can pass symbol layout method corresponds method in controller return layout name this:

layout :my_method  def my_method     'layout_1' end 

i want have similar functionality likewise pass symbol classes method , class should call corresponding function , use return value, this

myclass.foo :my_method  def my_method     'layout_1' end 

i've read posts[1] tell me need pass

myclass.foo(method(:my_method)) 

which find ugly , inconvenient. how rails here different allowing pass symbol without wrapper? can achieved rails it?

[1] how implement "callback" in ruby?

if want pass :symbol method, have make assumptions method named :symbol 1 want called you. it's either defined in class of caller, or outer scope. using binding_of_caller gem, can snag information , evaluate code in context.

this surely has security implications, issues you! :)

require 'binding_of_caller'  class test    def foo(sym)     binding.of_caller(1).eval("method(:#{sym})").call   end  end  class other    def blork     t = test.new     p t.foo(:bar)     p t.foo(:quxx)   end    def bar     'baz'   end  end  def quxx   'quxx' end  o = other.new o.blork > "baz" > "quxx" 

Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -