开发者

When might a dispatch table be as good as method_missing in Ruby?

开发者 https://www.devze.com 2023-04-13 07:10 出处:网络
Are there any situations where a dispatch table, implemented as a hash of lambdas, might be as good, if not better, than over-riding Ruby\'s method_missing?I\'m asking because I used this technique to

Are there any situations where a dispatch table, implemented as a hash of lambdas, might be as good, if not better, than over-riding Ruby's method_missing? I'm asking because I used this technique today as I'm a comparative newbie with Ruby, but have previously had a Perl background, and the dispatch table example in Wikipedia is even implemented in Perl ;) See:

http://en.wikipedia.org/wiki/Dispatch_table

In any event, also, what are the drawbacks to using a dispatch table instead of method_missing. Maybe my Ruby code below gives a clue? It would seem that my dispatch table could grow quite large, and there's no way to access the lambdas it contains for use in another context. So maybe I'm answering my question to some extent, but I'm really interested in when a dispatch table might be a better solution than method_missing or other 开发者_运维技巧meta programming techniques, thanks

def dispatch_self_and_modified_ancestors(key, value, work_effort)
    dispatch_table = {
        :scheduled_completion_date => lambda {|work_effort, updated_value|
            modified_ancestors = []

            while work_effort.parent
                work_effort = work_effort.parent
                if updated_value > work_effort.scheduled_completion_date
                    work_effort.scheduled_completion_date = updated_value
                    work_effort.save
                    modified_ancestors.push work_effort
                else
                    break
                end
            end

            return modified_ancestors
        }
    }

    if dispatch_table.has_key?(key)
        return dispatch_table[key].call(work_effort, value)
    else
        return []
    end
end


If you are frequently calling something caught by method_missing, the act of searching for a nonexistent method may end up being a performance issue in your code. So a dispatch table might be one way of working around that.

Here's a good article describing the performance issues of method_missing and attempts at optimizing them: http://www.alef1.org/ruby/method_missing/

0

精彩评论

暂无评论...
验证码 换一张
取 消