ruby-on-rails - 返回子类常量数组的不同元素
问题描述
我有一个Parent
定义为常量数组的类COLUMNS
class Parent
COLUMNS = [
{ column: 'type', type: 'String' }
]
end
还有一个Child
具有相同常量名称的类称为COLUMNS
class Child < Parent
COLUMNS = [
{ column: 'type', type: 'String' },
{ column: 'user', type: 'String' },
{ column: 'password', type: 'String' }
]
end
如何Child
从类常量数组中仅获取类常量数组的非相同元素Parent
。IE,
# Expected output
[
{ column: 'user', type: 'String' },
{ column: 'password', type: 'String' }
]
解决方案
class Parent
COLUMNS = [
{ column: 'type', type: 'String' }
]
def self.fields
COLUMNS
end
end
class Child < Parent
COLUMNS = [
{ column: 'type', type: 'String' },
{ column: 'user', type: 'String' },
{ column: 'password', type: 'String' }
]
def self.fields
COLUMNS - super
end
fields
end
输出:
=> [{:column=>"user", :type=>"String"}, {:column=>"password", :type=>"String"}]
推荐阅读
- c++ - 如何设计具有不同类型通知和观察者的观察者模式?
- node.js - 在发送给客户端之前修改 api 响应
- python - 在类级别获取类名
- ember.js - 安装 ember-cli-content-policy 后控制台出现错误
- pandas - Python饼图/显示多列组合
- sql-server - SQL 选择语句到一个参数
- html - 使用 Tab 键聚焦时如何设置元素的样式?
- android - android studio上出现“无法安装intel haxm”的错误如何解决?
- spring - JPA join multiple table one to many and one to one
- angular - 根据条件显示图像