Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

boolean_attr_accessor

#5622

I'd like to propose adding a boolean_attr_accessor core extension to Module:

  class Foo
    boolean_attr_accessor :bar
  end

  foo = Foo.new
  foo.bar = "1"
  foo.bar? #=> true

I find myself needing this feature a lot, specifically when adding virtual boolean attributes to ActiveRecord models using them with form helpers in the view.

Patch attached with a rough version.

Thoughts?

Reported by Mark Dodwell · September 13th, 2010 @ 07:31 AM

State: wontfix
Milestone: none
Assigned to: nobody
Importance: Low

Activity

  1. Rohit Arondekar
    Rohit Arondekar
    • Importance changed from to Low

    Mark, I think you should also post on the core list: http://groups.google.com/group/rubyonrails-core You'll get more responses there as to whether this is a desired feature or not.

    September 13th, 2010 @ 07:38 AM

  2. Robert Pankowecki
    Robert Pankowecki
    • Tag changed from activesupport, attr_accessor, core_ext, patch to activesupport, attr_accessor, boolean, core_ext, patch

    I use such code for this:

    
    module Kernel
      def Boolean(b)
        return b if [FalseClass, TrueClass, NilClass].any?{|k| b.is_a?(k)}
        case b
        when /^1$/, /^true$/i , /^yes$/i then true
        when /^0$/, /^false$/i , /^no$/i then false
        else
          raise ArgumentError, "Unknown conversion to boolean type from: #{b.class}, Inspect: #{b.inspect}"
        end
      end
    end
    
    def bar=(value)
      write_attribute(:bar, Boolean(value))
    end
    

    September 14th, 2010 @ 08:38 AM

  3. Gaston Ramos
    Gaston Ramos

    I like the idea, but I'm not sure if it is right to take a lot of values as false

    September 15th, 2010 @ 10:17 AM

  4. Aditya Sanghi
    Aditya Sanghi

    You may want to make this a plugin first? If it's a really popular plugin, perhaps it will get included in the future.

    October 6th, 2010 @ 06:56 PM

  5. Ryan Bigg
    Ryan Bigg
    • State changed from new to wontfix

    Yes, please make this a plugin.

    October 6th, 2010 @ 09:47 PM