legendary_rob
legendary_rob

Reputation: 13002

Ruby/Rails ActiveRecord attribute find boolean

I am looking for a nice way to find if a ActiveRecord attribute is a boolean, i have this method here which will check of an summary attribute exists or has data, it does this by the value.nil? || value.zero? but now we have an exception where the value could be a boolean. so it blows up with a NoMethodError: undefined method zero?' for false:FalseClass

def self.summary_attribute_status(element)
  # Check if all summary attributes zero or nil
  result = element.class.attributes_for_tag(:summary_attributes).all? do |attribute| 
    value = element.send(attri bute)
    next element
    value.nil? || value.zero? 
  end
  return result ? nil : 'something'
end

I could do it like this:

value.nil? || value.zero? || (!value.is_a? TrueClass || !value.is_a? FalseClass)

But its seems like there should be a better way of finding its general type, i tried finding if they shared a boolean type parent or superclass but they both inherit from Object < BasicObject. is there no other way?

Upvotes: 1

Views: 529

Answers (2)

spickermann
spickermann

Reputation: 106802

If you have for example a User class that has a boolean attribute admin than you can do something like this:

User.columns_hash['admin'].type 
# => :boolean

Read more about columns_hash here: http://api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html#method-i-columns_hash

Upvotes: 1

javiyu
javiyu

Reputation: 1474

There is another way to detect if a value is a boolean in ruby.

!!value == value #true if boolean

But I don't think there is any method built-in for that.

Upvotes: 2

Related Questions