Moriarty
Moriarty

Reputation: 159

How to resolve "no implicit conversion of Class into String" in rails?

I have a method in patch as below:

def applicable_resource_type(resource_type)
  if resource_type.include?('Student')
    student_setting
  else
    teacher_setting
  end
end

This method is called in another patch which checks whether the resource type is 'teacher' or 'student' and stores the boolean value in 'active'.

def exams
  School.new(resource: self).request if can_examine_students?
end

private

def can_examine_students?
  active = applicable_resource_type(self.class.name).is_active?
  if active && (self.is_a?(Teacher))
      active = belongs_to_school?
  end
  active
end

However the resource_type is passed as a String whereas in can_examine_students? it is passed as a class/module. Is there any way to make them both consistent?

I tried the following:

def applicable_resource_type(resource_type)
  if resource_type.include?(Student)
    student_setting
  else
    teacher_setting
  end
end

But it gave error as:

TypeError:
  no implicit conversion of Class into String

I also tried

resource_type.include?('Student'.constantize)

But it gave error same typerror.

Is there a way to resolve the above error and keep both consistent resource_type consistent?

Thanks

Upvotes: 0

Views: 2216

Answers (1)

Clara
Clara

Reputation: 2715

Actually, in the second code snippet, when you call applicable_resource_type(self.class.name) you also hand over a String, because class.name returns a string.

If you want to write the first method more elegantly, you can use is_a? which accepts a class name as an argument. It would look like this:

def applicable_resource_type(resource_type)
  if resource_type.is_a?(Student)
    ...

Note, that you pass Student as a class name. You then have to adapt the second code snippet too and just pass the class and not class.name. Hence,

def can_examine_students?
  active = applicable_resource_type(self.class).is_active?
...

Upvotes: 1

Related Questions