# Creating a "fluent" interface

**URL:** <https://www.ruby-forum.com/t/creating-a-fluent-interface/195907>\
**Category:** Ruby\
**Created:** [October 2, 2010, 4:09pm UTC](https://www.ruby-forum.com/t/creating-a-fluent-interface/195907 "2010-10-02T16:09:42Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![sentinel](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/fbc32d/32.png) [@sentinel](https://www.ruby-forum.com/u/sentinel)\
**Post date:** [October 2, 2010, 4:09pm UTC](https://www.ruby-forum.com/t/creating-a-fluent-interface/195907/1 "2010-10-02T16:09:42Z")

</div>

I’ve faced this issue several times. I have a method that adds a  
component to a container. Should it return self (for method chaining),  
or the component.

The problem arises when the method ‘add’ might create the component (for  
user’s convenience). The caller now needs the handle of the component to  
call methods on it. I obviously cannot have different return values in  
different classes in my library. Is there any way to have both !

here’s a dummy sample:

def add comp  
case comp  
when Component  
# just add it, or assign it  
@components \<\< comp  
when String  
# convenience method … complicated creation of component  
comp = Component.new( …, comp)  
@components \<\< comp

when Number  
…  
end

return self  
end

In cases, where the user sends a string, i create a component object but  
caller  
will have to be provided other ways of retrieving component.

I just came across an article :  
[FluentInterface](http://martinfowler.com/bliki/FluentInterface.html) in which the author  
creates this interface:

private void makeFluent(Customer customer) {  
customer.newOrder()  
.with(6, “TAL”)  
.with(5, “HPK”).skippable()  
.with(3, “LGV”)  
.priorityRush();  
}

It seems that with() returns the order object, however in HPK, he is  
able  
to call skippable() on the line item. Since the example given is Java, I  
don’t think that there’s a “method\_missing” available that can forward a  
call from component to self. Anyway, the same method “add” can exist in  
both container and component (as in the case of a Tree object).

Look forward to your thoughts. rk.
