In my rails (4.2.1) app, I have a Type (model) that contains records with :name of "string", "integer", etc.
I want the user to be able to pass in values and check if it is a valid object of a given type. So, the pseudocode is:
check_value(:integer, "1") #=> true
check_value(:integer, "foo") #=>false
I would like to add new types over time which have their own logic to check_value for that type.
Here are a few alternatives I have looked at:
1 Add one method per type directly to Type model -
# app/models/type.rb
# inside class Type...
def check_string_value(val)
true
end
def integer_value(val)
begin
Integer(val)
rescue
return false
end
return true
end
This would work, but would require me to modify the type.rb file each time a new field type is added, which I would like to avoid.
2 per object methods in a file per type:
# lib/types/integer_type/integer_type.rb
int = Type.where(name: "integer").first
class << int
def check_value(val)
begin
Integer(val)
rescue
return false
end
return true
end
end
The problem with this is that I cannot call that particular instance of the integer type to pass in the verification call, since I do not construct it in my calling code.
So, neither of these seems ideal - I would like a technique that delegates the verify call from type.rb to the individual type to handle. Is this possible? How could I do it?