NothingToSeeHere NothingToSeeHere - 1 month ago 6
Ruby Question

find model class of array in hash rails 4

I am trying to figure out WHICH model is left in an array so that I can make conditional statements using that model.

set_hash = {
some_array_one: RedModel.some_scope,
some_array_two: BlueModel.some_scope,
some_array_three: GreenModel.some_scope
}


Assuming this hash has

some_array_one.count = 0,
some_array_two.count = 5,
some_array_three.count = 0,


Then the answer to set_class should equal: BlueModel

This is how I've tried to find that answer

set_class = set_hash.reject{|k, v| v.count.zero?}.map{|k, v| v.first.class.name}


However, what I get is:

["BlueModel"]


How do I constantize that string-in-array (probably not the correct term.)
When I try to use constantize, I get this error:

NoMethodError: undefined method `constantize' for ["Item"]:Array

Answer

How do I constantize that string-in-array (probably not the correct term.)

There is actually a method called constantize that does exactly what it sounds like it does:

"BlueModel".constantize
#=> BlueModel

Actually, it is string only because you are calling v.first.class.name, remove the name call and you'll get a model itself.

set_class =  set_hash.reject{ |k, v| v.count.zero?}.map{ |k, v| v.first.class.name }.map(&:constatize).first
set_class =  set_hash.reject{ |k, v| v.count.zero?}.map{ |k, v| v.first.class }.first