使用Rails时在Ruby中处理常量的最佳方法是什么?

编程入门 行业动态 更新时间:2024-10-20 05:40:58
本文介绍了使用Rails时在Ruby中处理常量的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一些常量,它们代表模型中一个字段中的有效选项。在Ruby中处理这些常数的最佳方法是什么?

I have some constants that represent the valid options in one of my model's fields. What's the best way to handle these constants in Ruby?

推荐答案

您可以为此目的使用数组或哈希(在您的环境中) .rb):

You can use an array or hash for this purpose (in your environment.rb):

OPTIONS = ['one', 'two', 'three'] OPTIONS = {:one => 1, :two => 2, :three => 3}

或一个枚举类,它允许您枚举常量和键用于关联它们:

or alternatively an enumeration class, which allows you to enumerate over your constants as well as the keys used to associate them:

class Enumeration def Enumeration.add_item(key,value) @hash ||= {} @hash[key]=value end def Enumeration.const_missing(key) @hash[key] end def Enumeration.each @hash.each {|key,value| yield(key,value)} end def Enumeration.values @hash.values || [] end def Enumeration.keys @hash.keys || [] end def Enumeration.[](key) @hash[key] end end

然后可以从中得出:

class Values < Enumeration self.add_item(:RED, '#f00') self.add_item(:GREEN, '#0f0') self.add_item(:BLUE, '#00f') end

并像这样使用:

Values::RED => '#f00' Values::GREEN => '#0f0' Values::BLUE => '#00f' Values.keys => [:RED, :GREEN, :BLUE] Values.values => ['#f00', '#0f0', '#00f']

更多推荐

使用Rails时在Ruby中处理常量的最佳方法是什么?

本文发布于:2023-11-26 13:14:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634001.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:常量   方法   Rails   Ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!