Class: ArEnums::Base

Inherits:
Object show all
Extended by:
OptionsHelper
Includes:
Comparable
Defined in:
lib/ar_enums/base.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from OptionsHelper

add_option, extract_values_and_options

Constructor Details

#initialize(attrs = {}) ⇒ Base

Returns a new instance of Base.



9
10
11
12
13
# File 'lib/ar_enums/base.rb', line 9

def initialize attrs = {}
  @id = attrs.delete(:id).to_i
  @name = attrs.delete(:name).to_s
  @extra_columns = attrs.reject { |k, _| [:enum_class, :on_style_not_matched].include?(k) }
end

Instance Attribute Details

#extra_columnsObject (readonly)

Returns the value of attribute extra_columns.



6
7
8
# File 'lib/ar_enums/base.rb', line 6

def extra_columns
  @extra_columns
end

#idObject (readonly)

Returns the value of attribute id.



6
7
8
# File 'lib/ar_enums/base.rb', line 6

def id
  @id
end

#nameObject (readonly)

Returns the value of attribute name.



6
7
8
# File 'lib/ar_enums/base.rb', line 6

def name
  @name
end

Class Method Details

.[](name_or_id) ⇒ Object Also known as: find_by_id



53
54
55
# File 'lib/ar_enums/base.rb', line 53

def self.[] name_or_id
  all.detect { |enum| enum == name_or_id }
end

.create_from(value, values, options) ⇒ Object



15
16
17
18
19
20
21
22
23
24
# File 'lib/ar_enums/base.rb', line 15

def self.create_from value, values, options
  required_attrs = case value
  when String, Symbol
    { name: value }
  else
    value
  end
  required_attrs[:id] ||= values.index(value) + 1
  new options.merge(required_attrs)
end

.enumeration(*config, &block) ⇒ Object



48
49
50
51
# File 'lib/ar_enums/base.rb', line 48

def self.enumeration *config, &block
  add_option config, class_name: self
  define_enums_getter ArEnums::Factory.make_enums(*config, &block)
end

.find_all_by_id(ids, options = {}) ⇒ Object



60
61
62
# File 'lib/ar_enums/base.rb', line 60

def self.find_all_by_id ids, options = {}
  all.select { |enum| ids.include? enum.id }
end

Instance Method Details

#<=>(other) ⇒ Object



36
37
38
# File 'lib/ar_enums/base.rb', line 36

def <=> other
  id <=> other.id
end

#==(other) ⇒ Object Also known as: eql?



26
27
28
29
# File 'lib/ar_enums/base.rb', line 26

def == other
  return id == other.id if other.is_a?(Base)
  [id.to_s, name].include?(other.to_s)
end

#hashObject



32
33
34
# File 'lib/ar_enums/base.rb', line 32

def hash
  id.hash
end

#in?(*enums) ⇒ Boolean

Returns:

  • (Boolean)


64
65
66
# File 'lib/ar_enums/base.rb', line 64

def in? *enums
  enums.any? { |e| self == e }
end

#to_sObject



40
41
42
# File 'lib/ar_enums/base.rb', line 40

def to_s
  try_labelize(self, :desc) || try_labelize(name, :titleize)
end

#to_symObject



44
45
46
# File 'lib/ar_enums/base.rb', line 44

def to_sym
  name.to_sym
end