conditional chaining in ruby

后端 未结 9 2184
一生所求
一生所求 2020-12-13 20:30

Is there a good way to chain methods conditionally in Ruby?

What I want to do functionally is

if a && b && c
 my_object.some_method_b         


        
9条回答
  •  被撕碎了的回忆
    2020-12-13 21:16

    Although the inject method is perfectly valid, that kind of Enumerable use does confuse people and suffers from the limitation of not being able to pass arbitrary parameters.

    A pattern like this may be better for this application:

    object = my_object
    
    if (a)
      object = object.method_a(:arg_a)
    end
    
    if (b)
      object = object.method_b
    end
    
    if (c)
      object = object.method_c('arg_c1', 'arg_c2')
    end
    

    I've found this to be useful when using named scopes. For instance:

    scope = Person
    
    if (params[:filter_by_age])
      scope = scope.in_age_group(params[:filter_by_age])
    end
    
    if (params[:country])
      scope = scope.in_country(params[:country])
    end
    
    # Usually a will_paginate-type call is made here, too
    @people = scope.all
    

提交回复
热议问题