热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

有更好的ruby方法吗-Isthereamorerubywayofdoingthis

Oksoihavethishelper我有这个助手defcurrent_company_title(Company.find_by_id(params[company_id]

Ok so i have this helper

我有这个助手

def current_company_title
 (Company.find_by_id(params["company_id"]).name rescue nil) || (@companies.first.name rescue nil) current_user.company.name
end

Basically what I am achieving with this is the following ...

基本上,我所取得的成果是……

If the param["company_id"] exists then try to get the company and if not then if @companies exists grab the first company name and if not then get the current users company name

如果param["company_id"]存在,则尝试获取公司,如果没有,则获取第一个公司名称,如果没有,则获取当前用户的公司名称

This works but the rescues seem like a hack...any idea on another way to achieve this

这是可行的,但救援看起来像黑客。有没有别的办法

6 个解决方案

#1


3  

Indeed rescue is kind of a hack, id' probably split it up into two methods and then use try to fetch the name if available: http://api.rubyonrails.org/classes/Object.html#method-i-try

实际上,save是一种黑客,id'可能将它分为两种方法,然后使用try来获取名称(如果有的话):http://api.rubyonrails.org/classes/Object.html method-i-try

def current_company
  @current_company ||= Company.find_by_id(params[:company_id]) || @companies.try(:first) || current_user.try(:company)
end

def current_company_name
  current_company.try(:name)
end

#2


2  

Company.find_by_id(params["company_id"]).name`

find and its derivates are meant to be used when you're sure-ish you'll have a positive result, and only in some cases (row was deleted, etc) errors. That's why it raises an exception. In your case, you're assuming it's gonna fail, so a regular where, which would return nil if no rows was found, would do better, and remove the first rescue

find和它的派生类应该在确定结果时使用,并且只有在某些情况下(删除行等)错误时才使用。这就是它引发一个例外的原因。在你的例子中,你假设它会失败,所以一个正则的where,如果没有找到行,它会返回nil,这样做会更好,并删除第一次救援

@companies.first.name rescue nil

could be replaced by

可以取代

@companies.first.try(:name)

I'll let you check the api for more on the topic of try. It's not regular ruby, it's a Rails addition.

我将让您检查api以获得更多关于try的主题。它不是普通的ruby,而是Rails的添加。

#3


2  

Less "magic", simple code, simple to read:

少了“魔法”,代码简单,易读:

def current_company_title
 company = Company.where(id: params["company_id"]).presence
 company ||= @companies.try(:first)
 company ||= current_user.company
 company.name
end

Ps. Not a big fan of Rails' try method, but it solves the problem.

对Rails的尝试方法并不热衷,但它解决了问题。

#4


1  

def current_company_title
    if params["company_id"]
        return Company.find_by_id(params["company_id"]).name
    elsif @companies
        return @companies.first.name
    else
        return current_user.company.name
    end
end

#5


1  

The rescues are a hack, and will obscure other errors if they occur.

救援是一种手段,一旦发生其他错误,就会被掩盖。

Try this:

试试这个:

(Company.find_by_id(params["company_id"].name if Company.exists?(params["company_id"]) ||
(@companies.first.name if @companies && @companies.first) || 
current_user.company.name

then you can extract each of the bracketed conditions to their own methods to make it more readable, and easier to tweak the conditions:

然后,您可以将每个括号括起来的条件提取到它们自己的方法中,使其更具可读性,并且更容易调整条件:

company_name_from_id(params["company_id"]) || name_from_first_in_collection(@companies) || current_user_company_name

def company_name_from_id(company_id)
  company=Company.find_by_id(company_id)
  company.name if company
end

def name_from_first_in_collection(companies)
  companies.first.name if companies && companies.first
end

def current_user_company_name
  current_user.company.name if current_user.company
end

#6


0  

[Company.find_by_id(params["company_id"]),
  @companies.to_a.first,
  current_user.company
].compact.first.name

推荐阅读
  • 微软头条实习生分享深度学习自学指南
    本文介绍了一位微软头条实习生自学深度学习的经验分享,包括学习资源推荐、重要基础知识的学习要点等。作者强调了学好Python和数学基础的重要性,并提供了一些建议。 ... [详细]
  • GetWindowLong函数
    今天在看一个代码里头写了GetWindowLong(hwnd,0),我当时就有点费解,靠,上网搜索函数原型说明,死活找不到第 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • CSS3选择器的使用方法详解,提高Web开发效率和精准度
    本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • 本文详细介绍了Spring的JdbcTemplate的使用方法,包括执行存储过程、存储函数的call()方法,执行任何SQL语句的execute()方法,单个更新和批量更新的update()和batchUpdate()方法,以及单查和列表查询的query()和queryForXXX()方法。提供了经过测试的API供使用。 ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • ZSI.generate.Wsdl2PythonError: unsupported local simpleType restriction ... [详细]
  • 推荐系统遇上深度学习(十七)详解推荐系统中的常用评测指标
    原创:石晓文小小挖掘机2018-06-18笔者是一个痴迷于挖掘数据中的价值的学习人,希望在平日的工作学习中,挖掘数据的价值, ... [详细]
author-avatar
爱音乐的李雪梅
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有