Class: TinyStruct

Inherits:
Object
  • Object
show all
Defined in:
lib/tiny_struct.rb,
lib/tiny_struct/version.rb,
lib/tiny_struct/memory_cache.rb,
lib/tiny_struct/object_space_cache.rb

Overview

A class for encompassing the simple pattern of required and ordered parameters and their associated reader methods. To create a new class, run:

class User < TinyStruct.new(:first_name, :last_name)
  def full_name
    "#{first_name} #{last_name}"
  end
end

This will create a class that now has ‘attr_reader`s for `first_name` and `last_name`, as well as having an initializer that sets those values.

Defined Under Namespace

Classes: MemoryCache, ObjectSpaceCache

Constant Summary collapse

ATTRIBUTE_PATTERN =
/\A[a-z][a-zA-Z0-9_]*\z/
VERSION =
'0.0.1'.freeze

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Class Attribute Details

.cacheObject

Returns the value of attribute cache.



38
39
40
# File 'lib/tiny_struct.rb', line 38

def cache
  @cache
end

Class Method Details

.configure {|_self| ... } ⇒ Object

Yields ‘TinyStruct` to a block such that you can toggle configuration settings. For example:

TinyStruct.configure do |config|
  config.cache = false
end

Yields:

  • (_self)

Yield Parameters:

  • _self (TinyStruct)

    the object that the method was called on



63
64
65
# File 'lib/tiny_struct.rb', line 63

def configure
  yield self
end

.new(*members) ⇒ Object

Builds a new ‘TinyStruct` subclass based on the given members. The given members must be symbols that represents names that could otherwise be used as argument names.



43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/tiny_struct.rb', line 43

def new(*members)
  success =
    members.all? do |attribute|
      attribute.is_a?(Symbol) && attribute.match?(ATTRIBUTE_PATTERN)
    end

  unless success
    raise ArgumentError, 'arguments to TinyStruct::new must be valid ' \
                         'attribute names represented as symbols'
  end

  class_cache[members] ||= define_class(members)
end

Instance Method Details

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

‘true` if the members of the other `TinyStruct` instance are equal to the values of this `TinyStruct` instance.

Returns:

  • (Boolean)


21
22
23
24
25
26
27
# File 'lib/tiny_struct.rb', line 21

def eql?(other)
  other.class.respond_to?(:members) &&
    self.class.members == other.class.members &&
    self.class.members.all? do |attribute|
      public_send(attribute) == other.public_send(attribute)
    end
end

#inspectObject Also known as: to_s



30
31
32
33
34
# File 'lib/tiny_struct.rb', line 30

def inspect
  pairs =
    self.class.members.map { |name| "@#{name}=#{public_send(name).inspect}" }
  "#<#{self.class.name || 'TinyStruct'} #{pairs.join(' ')}>"
end