简体   繁体   中英

how to call methods defined in module inside a class in rails 4

My code:

I have used AuthenticationRelated only in the ApplicationHelper also signed_in? in is_admin? is from Devise Gem.

module AuthenticationRelated
 def is_admin?
    athu = false
    if signed_in?
      current_user.roles.each do |role|
        if role.name == 'admin'
          athu = true
        end
      end
    end
    athu
  end
end

Now I have a class SalesReportsGrid which I need to be able to access the is_admin? So this is what I have done:

class SalesReportsGrid

  include Datagrid
  include AuthenticationRelated

  scope do
    if is_admin?
      Sales.joins(product: [ category: [:access_lists] ] )
    else
     ....
    end
  end
....
end

Now when I run this I get the following error:

undefined method `is_admin?` for SalesReportsGrid:Class

Edit

When I add extend AuthenticationRelated

This is what I get:

undefined method `signed_in?` for SalesReportsGrid:Class

I am really confused, can someone please have a look and suggest something? Thanks

If you include module, you add its methods to instances of the class where you used include . To make module methods 'class methods' (ie singleton methods of class), you should use extend :

extend AuthenticationRelated

You need to be explicit in using current_user to define grid scope.

Here is example:

def index
  @grid = SalesReportGrid.new(params[:sales_report_grid]) do |scope|
    unless current_user.admin?
      scope.where_accessible_by(current_user)
    end
  end
end

It allows you to be more explicit and don't move access control to the grid and leave it in controller like it use to happen in other places.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM