Issue #15829 has been updated by okuramasafumi (Masafumi OKURA).


How about `call`ing a condition object if it's callable instead of simply using value as a condition?

```
class Object
  def then_if(condition, &block)
    if condition
      if (condition.respond_to?(:call) && condition.call(self)) || condition
        self.then(&block)
      end
    else
      self
    end
  end
end
```

Then we can do something like this:

```
'str'.then_if(Proc.new {|str| str.downcase == str}) {|str| str.upcase}
```

I know it's complicated and not beautiful, but it's an idea anyway.

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

* Author: foonlyboy (Eike Dierks)
* Status: Rejected
* 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:

```ruby
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:

```ruby
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>