سؤال

I am using Ruby on Rails 3.2.9 and Ruby 1.9.3. I have an array of symbols and a model class (ActiveModel) having those symbols (more others) as boolean attributes. Given a class instance I would like to retrieve all its attribute names for which the value is true. That is:

# 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]

How can I make that?

هل كانت مفيدة؟

المحلول 2

If you have the list of symbols you can iterate through them and select the ones that are true

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

If you don't have the list of symbols you want you can simply iterate through all the attributes of the model

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

نصائح أخرى

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top