Skip to content

Instantly share code, notes, and snippets.

@ainame
Created August 27, 2015 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ainame/deb182457b740d407029 to your computer and use it in GitHub Desktop.
Save ainame/deb182457b740d407029 to your computer and use it in GitHub Desktop.
ChainQuery allow you to build query by method chains.
class ChainQuery
def initialize(init_value)
@init_value = init_value
@filters = []
end
def add_filter(&block)
@filters << block
self
end
def value
@filters.reduce(@init_value) {|last_value, filter| filter.call(last_value) }
end
end
@ainame
Copy link
Author

ainame commented Aug 27, 2015

class Calculator < ChainQuery
  def add_1
    add_filter {|val| val + 1}
  end

  def sub_1
    add_filter {|val| val - 1}
  end
end

Calculator.new(0).add_1.add_1.sub_1.value #=> 1
Calculator.new(10).sub_1.add_1.sub_1.value #=> 9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment