I'm trying to implement a funky version of method chaining. Returning the instance of the class after each function call is easy, you just do
def chainable_method
some_code()
self
end
My idea is that the methods you can call depend on the previous method call. I'm trying to achieve this by returning an object belonging to the containing object. The contained object will have a few special methods, and then implement method_missing to return the containing object's instance.
Edit: The child object has some state associated with it that should be in itself, and not the parent. It might not have been clear previously as to why I need a whole instance for just method calls.
super is irrelevant in this case because the contained object doesn't inherit from the containing object, and I wouldn't want to call the containing object's methods on the contained object anyway - I want to call the containing object's methods on the containing object itself. I want the containing object, not the containing object class.
Not sure if this is possible.
Edit: reworded everything to use "containing/contained object" instead of the completely incorrect parent/child object. Also, I'm using 1.9.3, if that matters. Version isn't important, I can change if needed.
My explanation was probably unclear. Here's the code:
class AliasableString
def initialize(string)
@string = string
end
def as(aka)
@aka = aka
end
def has_aka?
[email protected]?
end
# alias is a reserved word
def aka
@aka
end
def to_s
@string + (self.has_aka? ? (" as " + @aka) : "")
end
end
class Query
def initialize
@select_statements = Array.new
end
def select(statement)
select_statement = AliasableString.new(statement)
@select_statements.push(select_statement)
select_statement
end
def print
if @select_statements.size != 0
puts "select"
@select_statements.each_with_index {| select, i|
puts select
}
end
end
end
# Example usage
q0 = Query.new
q0.select("This is a select statement")
.select("Here's another one")
.as("But this one has an alias")
.select("This should be passed on to the parent!")
q0.print
I haven't yet fully implemented print. AliasableString needs to have @string and @aka separate so I can pull them apart later.
Parent.newor you have an instance of parent already and may return it.the child object doesn't inherit from the parent...I want the parent instance, not the parent class... wat.