简体   繁体   中英

Ruby stringify method chain

Let's say I have a Ruby object called Foo . This code will result in the following:

Foo.bar.baz #=> "bar baz"

How could I achieve this. (I know this seems pointless and probably breaks several conventions, I was just curious to see how this could be achieved.

A horrible hackey way to do this horrible hackey thing would be to use method_missing.

class Ouch
  def initialize
    @log = ""
  end
  def method_missing(method)
    if @log.empty?
      @log = method.to_s
    else
      @log += " #{method}"
    end
    self
  end

  def run 
    @log
  end
end

Now you can do:

Foo = Ouch.new
Foo.bar.baz.run
>> "bar baz"

What this says is if you pass an instance of Ouch a method it doesn't know (anything but run), take the new of that method and append it to the log string stored as an instance variable (@log) inside your instance. Finally, you need some extractor function like run to let the object know that you are done and would like to return the accumulated log. Hope this helps.

[EDIT]

To be entirely clear, method_missing is a "magic" Ruby function that gets called whenever a method is called on an object that the object does not recognize.

class Object
    def bar; [(instance_of?(String)? self : nil), "bar"].join(" ") end
    def baz; [(instance_of?(String)? self : nil), "baz"].join(" ") end
end
Foo.bar.baz #=> "bar baz"
Foo.baz.bar #=> "baz bar"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM