Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if an argument is an instance of model or the class in Rails?

I have a helper method which generates "crud" links for a resource. Right now it only handles edit and destroy. But I want to refactor it so that it would create a new link if passed a model class instead of an instance.

Desired output:

> crud_links_for_resource(Product)
> { :new => '<a href="/products/new">Create a new product.</a>'}

What is the best way to check if a variable is the class of a model or an instance? I thought of using duck typing (resource.respond_to? :new_record?) but is there a better way?

module PermissionsHelper
  # Generates a hash of links to edit or destroy a resource
  # @param [ActiveModel] resource
  # @param [Actions] a list of crud actions to create links to
  # @param [Hash] kwargs optional hash to pass to link to
  # @option kwargs [String] :controller - controller name to use.
  #   Otherwise a guess is performed based on the resource class name.
  # @option kwargs [Hash] url_extras - passed to url_for. Can be used for nested resources.
  # @return [Hash] a list of links to actions which the user is allowed to perform
  def crud_links_for_resource(resource,  actions = [:destroy, :edit], **kwargs)
    privledges = actions.keep_if { |action| can? action, resource }
    privledges.each_with_object({}) do |action, hash|
      i18n_key = resource.model_name.i18n_key
      txt = t("#{ i18n_key }.#{action}")
      controller = kwargs[:controller] || i18n_key.to_s.pluralize
      url_extras = kwargs[:url_extras] || {}
      options = kwargs.except(:controller, :url_extras)
      case action
        when :destroy
          options.merge!(method: :delete, confirm: t("#{ i18n_key }.confirm_#{action}"))
        else
      end
      hash[action] = link_to(txt, { action: action, controller: controller, id: resource }.merge(url_extras) ,options)
    end
  end
end
like image 405
max Avatar asked Dec 14 '22 14:12

max


2 Answers

if myobject.is_a?(Foo)
  #it's an instance of foo
else
  #it's something else
end

or

if myobject.is_a?(Class)
  #it's a class
else
  #it's not
end
like image 156
Max Williams Avatar answered Feb 12 '23 12:02

Max Williams


In case you want to make sure that the object in question is not only any class but a model class - i.e. a (direct or indirect) descendant of ActiveRecord::Base:

my_object.is_a?(Class) && my_object < ActiveRecord::Base
like image 27
Mayinx Avatar answered Feb 12 '23 10:02

Mayinx