Creating a "fluent" interface

Discussion in 'Ruby' started by Rahul Kumar, Oct 2, 2010.

  1. Rahul Kumar

    Rahul Kumar Guest

    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 :
    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.
    --
    Posted via http://www.ruby-forum.com/.
     
    Rahul Kumar, Oct 2, 2010
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Rhino
    Replies:
    30
    Views:
    1,958
    Rhino
    Dec 12, 2004
  2. shinya
    Replies:
    1
    Views:
    613
    Stefan Ram
    Apr 21, 2008
  3. jeff m

    Fluent page navigation

    jeff m, Jul 18, 2008, in forum: ASP .Net
    Replies:
    0
    Views:
    530
    jeff m
    Jul 18, 2008
  4. Nephi Immortal

    Construction Time as Fluent Pattern

    Nephi Immortal, Feb 23, 2012, in forum: C++
    Replies:
    5
    Views:
    452
    Krice
    Feb 25, 2012
  5. Ben Last
    Replies:
    0
    Views:
    60
    Ben Last
    Jul 15, 2013
Loading...

Share This Page