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, id or name

Example:

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


12
13
14
15
16
17
18
# File 'lib/enumerations/finder_methods.rb', line 12

def find(key)
  case key
  when Symbol then find_by_key(key)
  when String then find_by_key(key.to_sym) || find_by_id(key.to_i)
  when Fixnum then find_by_id(key)
  end
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...>


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

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

#find_by_id(id) ⇒ Object



45
46
47
# File 'lib/enumerations/finder_methods.rb', line 45

def find_by_id(id)
  _values[_symbol_index.key(id)]
end

#find_by_key(key) ⇒ Object



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

def find_by_key(key)
  _values[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...>


27
28
29
# File 'lib/enumerations/finder_methods.rb', line 27

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