Class: StaticCollection::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/static_collection.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Base

Returns a new instance of Base.



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

def initialize(attributes = {})
  @attributes = attributes
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



58
59
60
# File 'lib/static_collection.rb', line 58

def attributes
  @attributes
end

Class Method Details

.allObject



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

def self.all
  defaults = instance_variable_get(:@defaults)
  instance_variable_get(:@source).map { |s| new(defaults.merge(s)) }
end

.countObject



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

def self.count
  all.size
end

.find_by(opts) ⇒ Object



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

def self.find_by(opts)
  all.find { |instance| opts.all? { |k, v| instance.send(k) == v } }
end

.set_source(source, defaults: {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/static_collection.rb', line 6

def self.set_source(source, defaults: {})
  raise "Source must be an array" unless source.is_a?(Array)

  instance_variable_set(:@defaults, defaults.stringify_keys)
  instance_variable_set(:@source, source.map(&:stringify_keys))
  raise "Source must have at least one value" unless count > 0

  all.first.attributes.each do |attribute_name, attribute_value|
    # Class methods
    define_singleton_method("find_by_#{attribute_name}") do |value|
      ActiveSupport::Deprecation.warn(
        "find_by_#{attribute_name} is deprecated for StaticCollection, " \
        "use find_by(#{attribute_name}: [value])",
      )
      all.find { |instance| instance.send(attribute_name) == value }
    end
    define_singleton_method("find_all_by_#{attribute_name}") do |value|
      ActiveSupport::Deprecation.warn(
        "find_all_by_#{attribute_name} is deprecated for StaticCollection, " \
        "use where(#{attribute_name}: [value])",
      )
      all.select { |instance| instance.send(attribute_name) == value }
    end

    # Instance methods
    send(:define_method, attribute_name) { attributes[attribute_name] }
    next unless attribute_value.is_a?(TrueClass) || attribute_value.is_a?(FalseClass)

    send(:define_method, "#{attribute_name}?") {
      attributes[attribute_name]
    }
  end
end

.where(opts) ⇒ Object



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

def self.where(opts)
  all.select { |instance| opts.all? { |k, v| instance.send(k) == v } }
end

Instance Method Details

#as_json(options = {}) ⇒ Object



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

def as_json(options = {})
  attributes.as_json(options)
end