Hi, I'm Hwee-Boon Yar

I write, ship and sell software products. iOS/OS X app developer based in Singapore, working remotely. This is my blog.

.

Need to run a code review on your codebase? Hire me

This is probably obvious to Ruby developers, but for us Objective C developers who are new to RubyMotion, I've found it common enough to define accessors for bools.

Bool accessors end with a question mark (?), so normally you do this:

class SomeClass
  attr_accessor :friendly

  def friendly?
    friendly
  end
end

or

class SomeClass
  attr_accessor :friendly
  alias_method :friendly?, :friendly
end

but with a little DSL:

class Class
  def bool_attr_accessor(*my_accessors)
    my_accessors.each do |accessor|
      define_method(("#{accessor}?").to_sym) do
        !!instance_variable_get("@#{accessor}")
      end

      define_method("#{accessor}=") do |accessor_value|
        instance_variable_set("@#{accessor}", accessor_value)
      end
    end
  end
end

You can do this instead:

class SomeClass
  bool_attr_accessor :friendly
end

Like this post? Follow me @hboon on Twitter.

.