Ruby 2.5 Object#yield_self.



New feature in Ruby 2.5


class Object
  def yield_self
    yield(self)
  end
end

Today example

CSV.parse(File.read(File.expand_path("data.csv"), __dir__))
   .map { |row| row[1].to_i }
   .sum

Now u can use it like


"data.csv"
  .yield_self { |name| File.expand_path(name, __dir__) }
  .yield_self { |path| File.read(path) }
  .yield_self { |body| CSV.parse(body) }
  .map        { |row|  row[1].to_i }
  .sum

Or in typical scenario


events = Event.upcoming
  events = events.limit(params[:limit])          if params[:limit]
  events = events.where(status: params[:status]) if params[:status]
  events

Now you can write


Event.upcoming
  .yield_self { |events| params[:limit]  ? events.limit(params[:limit]) : events }
  .yield_self { |events| params[:status] ? events.where(status: status) : events }

(c) https://mlomnicki.com//

Comments