Issue #15829 has been updated by foonlyboy (Eike Dierks).


A more complex example:

``` ruby
    scope :blacklisted_at, -> (seller=nil, flag=true) {
      then_if(! flag.nil?) {
        joins(:disk_seller_maps)
        .then_if(seller) {|q|
          q.where(disk_seller_map:{seller_id:seller})
        }
        .then_if(! flag) {|q|
          all.where.not(id: q)
        }
      }
    }

```

Not really sure if this does what I mean,
but it looks a lot more concise now.


Before that all that cases would have expanded to 6 cases,
but now it looks a lot more concise.

- then_if(! flag.nil?) shields from flag.nil?
- then_if(seller) only applies if a seller was given
- then_if(! flag) negates the query

This brings the code down from 2x3=6 variants,
to only two code blocks (the second one being trivial in this case)

















----------------------------------------
Feature #15829: Object#then_if(condition){}
https://bugs.ruby-lang.org/issues/15829#change-77926

* Author: foonlyboy (Eike Dierks)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
----------------------------------------
I'd like to propose some sugar to Object#then

There should be Object#then_if(condition, &block)
 
The block should only be applied when the condition is true,
otherwise the object should be returned without applying the block.

Rationale:

I frequently use Object#then with Rails to extend queries like this:

```
foo.then {|query|
  if(condition)
   query.where(zip:zap)
  else
   query
  end
}
```

by using the proposed Object#then_if the example could be simplified to:

```
foo.then_if(condition) {|query|
   query.where(zip:zap)
}
```

I believe that this also applies to a lot of other use cases,
i.e. only applying some transformation if some condition is true,
but otherwise leaving the result untouched.















-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>