I was reading another SO question Enums in Ruby and it had the following code snippet:
class Enum
private
def self.enum_attr(name, num)
name = name.to_s
define_method(name + '?') do
@attrs & num != 0
end
define_method(name + '=') do |set|
if set
@attrs |= num
else
@attrs &= ~num
end
end
end
public
def initialize(attrs = 0)
@attrs = attrs
end
def to_i
@attrs
end
end
As I understand this, this is defining a class method named enum_attr
, is that correct? What I'm unsure of is what it means to have the define_method
statements inside of the enum_attr
method.
Then later on that post it shows the class being extended as follows
class FileAttributes < Enum
enum_attr :readonly, 0x0001
enum_attr :hidden, 0x0002
end
I don't quite understand what this second part does - can someone explain?