如何检索值为true的实例属性名称?

时间:2012-12-22 12:21:29

标签: ruby-on-rails ruby ruby-on-rails-3 attributes data-retrieval

我正在使用Ruby on Rails 3.2.9和Ruby 1.9.3。我有一个符号数组和一个模型类(ActiveModel),这些符号(更多其他符号)作为布尔属性。给定一个类实例,我想检索其值为true的所有属性名称。那就是:

# Given an array of symbols
[:attr_1, :attr_2, :attr_3]

# Given a class instance
<#Model attr_1: true, attr_2: false, attr_3: false, attr_4: true, ... attr_N: true>

# Then I would like to return
[:attr_1, :attr_4, ..., :attr_N]

我该怎么做?

2 个答案:

答案 0 :(得分:1)

attrs = [:attr_1, :attr_2, :attr_3]

class Model
  def are_true?(attr_names)
    eval(attr_names.map {|a| "send(:#{a})"}.join(" && "))
  end
  def which_true?(attr_names)
    attr_names.map {|a| a if send(a) == true}.compact
  end
end

m = <#Model attr_1: true, attr_2: false, attr_3: false, attr_4: true, ... attr_N: true>

m.are_true?(attrs)  # evals if all given attr_names are true
m.which_true?(attrs) # returns array of attr_names which are true

答案 1 :(得分:0)

如果你有符号列表,你可以迭代它们并选择那些是真的

symbols = [:attr_1, :attr_2, :attr_3]
symbols.select {|sym| object.send(sym) == true }

如果您没有所需的符号列表,您可以简单地遍历模型的所有属性

symbols = object.attributes
symbols.select {|sym| object.send(sym) == true }