Class: Stave::Core::Lookup

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/stave/core/lookup.rb

Defined Under Namespace

Classes: InvalidVariantError

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(variant) ⇒ Lookup

Returns a new instance of Lookup.



10
11
12
13
14
15
# File 'lib/stave/core/lookup.rb', line 10

def initialize(variant)
  @variant = variant.to_sym

  validate_variant!
  set_attributes!
end

Instance Attribute Details

#variantObject (readonly)

Returns the value of attribute variant.



6
7
8
# File 'lib/stave/core/lookup.rb', line 6

def variant
  @variant
end

Class Method Details

.each_keyObject



32
33
34
# File 'lib/stave/core/lookup.rb', line 32

def each_key(&)
  keys.each(&)
end

.find_by(**attributes) ⇒ Object



65
66
67
# File 'lib/stave/core/lookup.rb', line 65

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

.keysObject



28
# File 'lib/stave/core/lookup.rb', line 28

def keys = variant_lookup.keys

.string_keysObject



30
# File 'lib/stave/core/lookup.rb', line 30

def string_keys = keys.map(&:to_s)

.variant(name, prefix: nil, suffix: nil, **attributes) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/stave/core/lookup.rb', line 36

def variant(name, prefix: nil, suffix: nil, **attributes)
  name = :"#{prefix}_#{name}" if prefix
  name = :"#{name}_#{suffix}" if suffix

  variant_lookup[name] = attributes

  define_singleton_method name, -> { new(name) }
end

.variant?(name) ⇒ Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/stave/core/lookup.rb', line 45

def variant?(name)
  variant_lookup.keys.include?(name)
end

.variant_lookupObject



53
54
55
# File 'lib/stave/core/lookup.rb', line 53

def variant_lookup
  @variant_lookup ||= {}
end

.variantsObject



49
50
51
# File 'lib/stave/core/lookup.rb', line 49

def variants
  variant_lookup.keys.map { |variant| new(variant) }
end

.where(**attributes) ⇒ Object



57
58
59
60
61
62
63
# File 'lib/stave/core/lookup.rb', line 57

def where(**attributes)
  variants.select do |variant|
    attributes.all? do |attribute, value|
      variant.send(attribute) == value
    end
  end
end

.with_options(scope: nil, **options) ⇒ Object



69
70
71
72
73
74
75
76
77
# File 'lib/stave/core/lookup.rb', line 69

def with_options(scope: nil, **options, &)
  merger = OptionMerger.new(self, options)

  merger.instance_eval(&)

  return if scope.nil?

  define_singleton_method scope, -> { where(**options) }
end

Instance Method Details

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



17
18
19
20
21
22
23
# File 'lib/stave/core/lookup.rb', line 17

def ==(other)
  case other
  when String, Symbol then variant == other.to_sym
  when Lookup then variant == other.variant
  else false
  end
end