I've got a single-table-inheritance setup where I have a single Controller (I felt having multiple would be duplicative). However, for some methods, I'd like to call into the subclasses of the models. I figured I could have the browser send a parameter that I'd write a case statement against. Something like:
case @model[:type]
when "A"
@results = Subclass1.search(params[:term])
when "B"
@results = Subclass2.search(params[:term])
...
end
Alternatively though, I learned that Ruby, in all it's trickery can create a model out of a string. Something like:
@results = params[:model].constantize.search(params[:term])
My question: is this a bad practice? I can imagine someone sneaky could craft a request that would get me to form an arbitrary internal object.. but I could confirm that the object is a subclass of the thing I want..
When doing this, i like to refactor it with case
, just to be very clear about my allowed inputs:
@results = case params[:model]
when 'page' then Page
when 'post' then Post
else raise 'finger'
end.search(params[:term])
If you have a whitelist of objects that you check it against before you do it, then you should be ok. You just always want to make sure you are santizing and validating input coming from external sources very throughly to protect yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With