Reputation: 4271
Example:
7.cars.2.doors
I will add the cars
method to Integer and it will return a CarBuilding
object.
This CarBuilding
object then needs to receive the message 2
which will do some processing and return itself.
Finally doors
will be called on this CarBuilding object
Any kind of fancy Meta Programming able to do this?
Note: I don't want to pass parameters. Just use method chaining.
Upvotes: 0
Views: 87
Reputation: 1174
Because names started with digit are not valid you can use underscore:
class CarBuilding
def method_missing(method, *args, &block)
raise NoMethodError unless method =~ /\A_\d*\z/
puts "do something with #{method[1..-1].to_i}"
return self
end
def doors
puts "doors"
end
end
class Integer
def cars
return CarBuilding.new
end
end
puts 7.cars._2.doors
Upvotes: 1
Reputation: 369458
No, this isn't possible.
Using normal message sending syntax, the message must be a valid identifier. 2
is not a valid identifier, identifiers can't start with a digit. This is simply not syntactically legal.
It is possible to define a method named 2
using metaprogramming. Note, however, that this is the name 2
and not the Integer
2
. Obviously, it is not possible to invoke such a method using normal message sending syntax (nor is it possible to define it using normal method definition syntax).
class CarBuilding
define_method(:'2') do
CarBuildingWithDoors.new(2)
end
end
7.cars.public_send(:'2').doors
Upvotes: 3