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:
Generating 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.
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 |
# File 'lib/enum/helpers/enum_attribute.rb', line 11 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 generate_methods overrider: :enum do # attribute reader reader, reader_without_enum = attr, :"#{attr}_without_enum" define_method(reader) do v = respond_to?(reader_without_enum) ? send(reader_without_enum) : super() (ev = e.get(v)).nil? ? Enum::EnumValue.new(e, v) : ev end # attribute writer writer, writer_without_enum = :"#{attr}=", :"#{attr}_without_enum=" 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 respond_to?(writer_without_enum) ? send(writer_without_enum, v) : super(v) end if [:qualifier] # generating scopes and questioning methods e.by_name.each do |n, ev| define_method("#{n}?") { send(attr) == ev } end end end e end |