Class: Flags

Inherits:
Enum show all
Defined in:
lib/nice_enum.rb

Overview

Base class for enumerations in which members can be or’d together to create combinations of them. For example, Unix file permissions can be represented as a flag enumeration with the members Read = 4, Write = 2 and Execute = 1. There are many samples in README.rdoc and samples/.

Instance Attribute Summary

Attributes inherited from Enum

#name, #value

Instance Method Summary collapse

Methods inherited from Enum

#<=>, default_value, each, #eql?, #hash, #method_missing, new, #old_respond_to?, #respond_to?

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Enum

Instance Method Details

#&(other) ⇒ Object

Returns the intersection of self and other.



165
166
167
# File 'lib/nice_enum.rb', line 165

def &(other)
	self.class.new(value & other)
end

#^(other) ⇒ Object

Bitwise-XORs self with other.



170
171
172
# File 'lib/nice_enum.rb', line 170

def ^(other)
	self.class.new(value ^ other)
end

#flagsObject

Returns the individual enumeration members that are contained in self. If the enumeration class contains a member with the value 0, that member is only included in the result if there aren’t any other members that are contained in self.



147
148
149
150
151
# File 'lib/nice_enum.rb', line 147

def flags
	result = self.class.select { |flag| value & flag != 0 }.sort
	result = [self.class.new(0)] if result.empty?
	result
end

#join(seperator = " | ") ⇒ Object Also known as: to_s

Joins the result of flags together.



154
155
156
# File 'lib/nice_enum.rb', line 154

def join(seperator = " | ")
	flags.map { |flag| flag.name }.join(seperator)
end

#|(other) ⇒ Object

Returns the combination of self and other.



160
161
162
# File 'lib/nice_enum.rb', line 160

def |(other)
	self.class.new(value | other)
end