Dynamic method calling in a helper for Rails
I have a helper module with a bunch of method calls in the format
def link_to_details_for_facebook(param1, param2)
def link_to_details_for_twitter(param1, param2)
def link_to_content_for_facebook(param1, param2)
def link_to_content_for_twitter(param1, param2)
is th开发者_如何学Goere a way to call one method such as, so I can dynamically call correct the helper method?
def link_to_type_for_social_network(param1, param2, type="details", social_network="facebook")
method("#{type}_url_to_#{social_network}(param1, param2)".to_sym).call
end
This just gives me the error
undefined method
details_to_facebook(param1, param2)' for class
ActionView::Base'
I'm not familiar with the method() method, but would have used send()
myself. Since you're defining the method names to start with "link_to..." then you'll need to make sure that gets added to the method call. I would go with something like this:
def link_to_type_for_social_network(param1, param2, type="details", social_network="facebook")
send("link_to_#{type}_for_#{social_network}", param1, param2)
end
精彩评论