gpt4 book ai didi

ruby-on-rails - 如何检查参数是模型的实例还是 Rails 中的类?

转载 作者:数据小太阳 更新时间:2023-10-29 07:46:10 25 4
gpt4 key购买 nike

我有一个辅助方法,可以为资源生成“crud”链接。现在它只处理编辑和销毁。但我想重构它,以便在传递模型类而不是实例时创建一个 new 链接。

期望的输出:

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

检查变量是模型类还是实例类的最佳方法是什么?我想过使用 duck typing (resource.respond_to? :new_record?) 但有更好的方法吗?

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

最佳答案

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

if myobject.is_a?(Class)
#it's a class
else
#it's not
end

关于ruby-on-rails - 如何检查参数是模型的实例还是 Rails 中的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30374945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com