Class: Levels::Group

Inherits:
Object
  • Object
show all
Includes:
MethodMissing
Defined in:
lib/levels/group.rb

Overview

A group is a set of key/value pairs containing your data.

Examples

group = Levels::Group.new(name: "Joe", age: 33)

group.name # => "Joe"
group.age  # => 33

Instance Method Summary collapse

Methods included from MethodMissing

#method_missing

Constructor Details

#initialize(data = {}, value_transformer = nil) ⇒ Group

Internal: Initialize a new group.

data - Hash of key/values for the group. value_transformer - Proc that takes (key, value) and returns value.



19
20
21
22
# File 'lib/levels/group.rb', line 19

def initialize(data = {}, value_transformer = nil)
  @values = Levels::KeyValues.new(data)
  @value_transformer = value_transformer || -> key, value { value }
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Levels::MethodMissing

Instance Method Details

#[](value_key) ⇒ Object

Public: Get the value for a key.

Returns the value. Raises Levels::UnknownKey if the key is not defined.



28
29
30
31
32
33
34
35
# File 'lib/levels/group.rb', line 28

def [](value_key)
  if @values.key?(value_key)
    key, value = @values.pair(value_key)
    @value_transformer.call(key.to_sym, value)
  else
    raise UnknownKey, "#{value_key.inspect} is not defined in #{self}"
  end
end

#defined?(key) ⇒ Boolean

Public: Determine if a key is defined.

Returns a Boolean.

Returns:

  • (Boolean)


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

def defined?(key)
  @values.key?(key)
end

#eql_hash?(hash) ⇒ Boolean

Returns:

  • (Boolean)


57
58
59
# File 'lib/levels/group.rb', line 57

def eql_hash?(hash)
  @values == Levels::KeyValues.new(hash)
end

#to_enumObject

Returns an Enumerator which yields [key, value].



49
50
51
52
53
54
55
# File 'lib/levels/group.rb', line 49

def to_enum
  Enumerator.new do |y|
    @values.each do |key, value|
      y << [key.to_sym, self[key]]
    end
  end
end

#to_sObject



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

def to_s
  "<Levels::Group>"
end