Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the method 'is_admin?' defined in my Rails app?

I have some code that calls

current_user.is_admin?

The code works fine, but I can't figure out where the is_admin? method is defined. I'm using Devise, CanCan, and role_model, but the method isn't in any of these projects' source code, or in mine...

I also tried finding the owner of the method by doing this in the Rails console:

current_user.method(:is_admin?).owner
=> #<Module:0x00000105253c98>

But that's not much help...

like image 700
Yarin Avatar asked Nov 10 '22 21:11

Yarin


1 Answers

I got the source location by doing:

current_user.method(:is_admin?).source_location

(Thanks to @BroiSatse for that)

That pointed me to this file in role_model: https://github.com/martinrehfeld/role_model/blob/master/lib/role_model/class_methods.rb

Turns out role_model creates methods dynamically based on assigned roles- so that's why it wasn't showing up in source...

From class_methods.rb:

# Defines dynamic queries for :role
#   #is_<:role>?
#   #<:role>?
#
# Defines new methods which call #is?(:role)
def define_dynamic_queries(roles)
  dynamic_module = Module.new do
    roles.each do |role|
      ["#{role}?".to_sym, "is_#{role}?".to_sym].each do |method|
        define_method(method) { is? role }
      end
    end
  end
  include dynamic_module
end
like image 138
Yarin Avatar answered Nov 15 '22 04:11

Yarin