Module: Enumerations::FinderMethods

Included in:
Base
Defined in:
lib/enumerations/finder_methods.rb

Instance Method Summary collapse

Instance Method Details

#find(key) ⇒ Object

Finds an enumeration by symbol or name

Example:

Role.find(:admin)  => #<Enumerations::Value: @base=Role, @symbol=:admin...>
Role.find('staff') => #<Enumerations::Value: @base=Role, @symbol=:staff...>


10
11
12
13
14
# File 'lib/enumerations/finder_methods.rb', line 10

def find(key)
  case key
  when Symbol, String, Enumerations::Base then find_by_key(key.to_sym)
  end || find_by_primary_key(key)
end

#find_by(**args) ⇒ Object

Finds an enumeration by defined attribute. Similar to ActiveRecord::FinderMethods#find_by

Example:

Role.find_by(name: 'Admin') => #<Enumerations::Value: @base=Role, @symbol=:admin...>


33
34
35
# File 'lib/enumerations/finder_methods.rb', line 33

def find_by(**args)
  where(**args).first
end

#find_by_key(key) ⇒ Object



37
38
39
# File 'lib/enumerations/finder_methods.rb', line 37

def find_by_key(key)
  _values[key]
end

#find_by_primary_key(primary_key) ⇒ Object



41
42
43
44
45
# File 'lib/enumerations/finder_methods.rb', line 41

def find_by_primary_key(primary_key)
  return value_from_symbol_index(primary_key.to_i) if primary_key.is_a?(String)

  value_from_symbol_index(primary_key)
end

#where(**args) ⇒ Object

Finds all enumerations which meets given attributes. Similar to ActiveRecord::QueryMethods#where.

Example:

Role.find_by(name: 'Admin') => #<Enumerations::Value: @base=Role, @symbol=:admin...>


23
24
25
# File 'lib/enumerations/finder_methods.rb', line 23

def where(**args)
  _values.values.select { |value| args.map { |k, v| value.attributes[k] == v }.all? }
end