Module: Lightning::Api

Defined in:
lib/lightning/api.rb

Class Method Summary collapse

Class Method Details

.create!(key, description = '') ⇒ Object



5
6
7
8
9
# File 'lib/lightning/api.rb', line 5

def self.create!(key, description = '')
  Feature.create!(key: key, description: description)
rescue StandardError
  raise ::Lightning::Errors::FailedToCreate, 'Failed to create new feature'
end

.delete(key) ⇒ Object



27
28
29
# File 'lib/lightning/api.rb', line 27

def self.delete(key)
  get(key).destroy
end

.enabled?(feature_key, entity) ⇒ Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/lightning/api.rb', line 45

def self.enabled?(feature_key, entity)
  Feature.where(key: feature_key).left_outer_joins(:feature_opt_ins).where("state = ? OR (state = ? AND lightning_feature_opt_ins.entity_id = ? AND lightning_feature_opt_ins.entity_type = ?)", Feature.states[:enabled_globally], Feature.states[:enabled_per_entity], entity.id, entity.class.to_s).exists?
end

.get(key) ⇒ Object



11
12
13
14
15
# File 'lib/lightning/api.rb', line 11

def self.get(key)
  Feature.find_by!(key: key)
rescue StandardError
  raise ::Lightning::Errors::FeatureNotFound, "Feature with key: #{key} not found"
end

.listObject



17
18
19
# File 'lib/lightning/api.rb', line 17

def self.list
  Feature.all
end

.opt_in(key, entity) ⇒ Object



35
36
37
# File 'lib/lightning/api.rb', line 35

def self.opt_in(key, entity)
  get(key).feature_opt_ins.find_or_create_by!(entity_id: entity.id, entity_type: entity.class.to_s)
end

.opt_ins(key) ⇒ Object



31
32
33
# File 'lib/lightning/api.rb', line 31

def self.opt_ins(key)
  get(key).feature_opt_ins.all.map(&:entity)
end

.opt_out(key, entity) ⇒ Object



39
40
41
42
43
# File 'lib/lightning/api.rb', line 39

def self.opt_out(key, entity)
  get(key).feature_opt_ins.find_by(entity_id: entity.id, entity_type: entity.class.to_s)&.destroy
rescue ActiveRecord::RecordNotFound
  raise ::Lightning::Errors::EntityNotFound, "Could not find entity with id #{entity.id} and type #{entity.class.to_s}"
end

.update(key, attributes) ⇒ Object



21
22
23
24
25
# File 'lib/lightning/api.rb', line 21

def self.update(key, attributes)
  get(key).update(attributes)
rescue ArgumentError
  raise ::Lightning::Errors::InvalidFeatureState, "Failed to update state. State must be one of the following: #{Feature.states.keys} "
end