In ruby I can say (I picked up Mongoid only for example)
class MyItem
include Mongoid::Document
include Mongoid::Timestamps
#.................
def method1(some_type)
raise "Not symbol" unless some_type.is_a?(Symbol)
raise "Unsupported some_type (#{some_type})" unless [:some_type1, :some_type2, :some_type3].include?(some_type)
min_time_to_update = 60*60
full_method_name = "#{some_type}_another_method".to_sym()
!!self.send(full_method_name)
end
end
and call it
result = MyItem.first.method1(:some_type2)
Here the method send is being used to call a type’s method by its name. But what if I want to do the following
def method1(type, arg1, arg2)
#check if it's a correct type....
# type might be either MyItem1 or MyItem2 or anything that has a method `method123`
"#{type}".method123(arg1, arg2)
end
How can I do that? How can I get access to the type by its name to call its method?
typebeing a string eg. ‘MyItem1’ or ‘MyItem2’?Try
Object.const_get(type).method123(arg1, arg2).