I’m wondering if there’s a way to return an object instead of a string when calling an object without any methods.
For instance:
class Foo
def initialize
@bar = Bar.new
end
end
Is there any way to define the Foo class so that the following happens:
foo = Foo.new
foo #returns @bar
In the specific case I’m interested in I’m using a presenter in a Rails view. The presenter sets up one main object and then loads a bunch of related content. The important part looks like this:
class ExamplePresenter
def initialize( id )
@example = Example.find( id )
end
def example
@example
end
...
end
If I want to return the example used by the ExamplePresenter I can call:
@presenter = ExamplePresenter.new(1)
@presenter.example
It would be nice if I could also return the example object by just calling:
@presenter
So, is there a way to set a default method to return when an object is called, like to_s but returning an object instead of a string?
If I understand correctly, you want to return the instance of
Examplewhen you call theExamplePresenterinstance. Such a direct mechanism does not exist in any language, and even if it did, it would block all access to theExamplePresenterinstance and its methods. So it is not logical.There is something you can do however. You can make the
ExamplePresenterclass delegate methods to theExampleinstance inside it. Effectively you do not get a realExamplefrom@presenterbut you get anExamplePresenterthat passes all eligible methods into its internalExampleeffectively acting in behalf of it.Some ways of doing this is:
method_missing
This will pass any method call down to the internal
Exampleif theExamplePresentercannot respond to it. Be careful, you may expose more than you want of the internalExamplethis way, and any method already defined onExamplePresentercannot be passed along.You can use additional logic inside
method_missingto limit exposure or pre/post process the arguments/return values.Wrapper methods
You can define wrapper methods on
ExamplePresenterthat do nothing but pass everything to the internalExample. This gives you explicit control on how much of it you want to expose.This gets tedious fast, but you can also add logic to alter arguments before passing it along to the
Exampleor post process the results.You can also mix and match the above two methods
Delegator library
There is a library in Ruby stdlib called Delegator built exactly for this purpose. You may look into it.