Created
May 24, 2016 02:28
-
-
Save thinkingserious/5f5c09b12a269d765e6bb6a200e2ea7b to your computer and use it in GitHub Desktop.
Fluent Interface in Ruby Using Method Chaining and Reflection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Fluent | |
def initialize(cache: nil) | |
@cache = cache ? cache : [] | |
end | |
# Reflection | |
def method_missing(name, *args, &block) | |
_(name.to_s) | |
end | |
# Build the cache, and handle special cases | |
def _(name) | |
Fluent.new(cache: @cache.push(name)) | |
end | |
# Final method call | |
def method() | |
@cache | |
end | |
end | |
fluent = Fluent.new | |
chain = fluent.hello.world | |
puts chain.method() | |
new_chain = chain.thanks._('for').all.the.fish | |
puts new_chain.method() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment