Module: Enum::Helpers::EnumAttribute
- Includes:
- EnumGenerator
- Included in:
- EnumColumn, Module
- Defined in:
- lib/enum/helpers/enum_attribute.rb
Instance Method Summary collapse
-
#attr_yinum(attr, name_or_enum, options = {}, hash = nil) ⇒ Object
(also: #attr_enum)
Bind an attribute to an enum by: Generating attribute reader and writer to convert to EnumValue.
Methods included from EnumGenerator
Instance Method Details
#attr_yinum(attr, name_or_enum, options = {}, hash = nil) ⇒ Object Also known as: attr_enum
Bind an attribute to an enum by:
attribute reader and writer to convert to EnumValue.
If :qualifier => true, generates questioning methods for every name in the enum.
If given a enum name (a symbol) and hash, also creates the enum.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/enum/helpers/enum_attribute.rb', line 10 def (attr, name_or_enum, = {}, hash = nil) # the first hash is either options or the hash if the options are missing hash, = , {} unless name_or_enum.is_a?(Enum) or hash # generating or getting the enum if name_or_enum.is_a?(Enum) e = name_or_enum else # generating the enum if the hash is not empty name_or_enum, hash if hash.any? e = const_get(name_or_enum) end # attribute reader reader, reader_without_enum = attr, :"#{attr}_without_enum" begin alias_method reader_without_enum, reader rescue NameError # reader does not exist no_reader = true end define_method(reader) do v = no_reader ? super() : send(reader_without_enum) (ev = e.get(v)).nil? ? Enum::EnumValue.new(e, v) : ev end # attribute writer writer, writer_without_enum = :"#{attr}=", :"#{attr}_without_enum=" begin alias_method writer_without_enum, writer rescue NameError # writer does not exist no_writer = true end define_method(writer) do |v| v = case when v.enum_value? then v.value # might be received from forms when v.nil?, v == "" then v else e[v].value end no_writer ? super(v) : send(writer_without_enum, v) end if [:qualifier] # generating scopes and questioning methods e.by_name.each do |n, ev| define_method("#{n}?") { send(attr) == ev } end end e end |