1

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?

legendary_rob
  • 12,792
  • 11
  • 56
  • 102
  • 2
    possible duplicate of [Check if Ruby object is a Boolean](http://stackoverflow.com/questions/3028243/check-if-ruby-object-is-a-boolean) – Can Can Sep 08 '14 at 10:13

2 Answers2

2

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.

javiyu
  • 1,336
  • 6
  • 9
  • this is a very clever little method, i think this will work. i did see it in the answer that was given in my comments section so ill mark it correct here, and upvote that other question. – legendary_rob Sep 08 '14 at 12:24
1

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

spickermann
  • 100,941
  • 9
  • 101
  • 131
  • Thats a really interesting method, in this case it wouldn't work because what your calling summary attributes on may not have the column name you specify summary attributes. but to inspect it individually this is ace – legendary_rob Sep 08 '14 at 12:16