Class: TinyStruct
- Inherits:
-
Object
- Object
- TinyStruct
- 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
-
.cache ⇒ Object
Returns the value of attribute cache.
Class Method Summary collapse
-
.configure {|_self| ... } ⇒ Object
Yields ‘TinyStruct` to a block such that you can toggle configuration settings.
-
.new(*members) ⇒ Object
Builds a new ‘TinyStruct` subclass based on the given members.
Instance Method Summary collapse
-
#eql?(other) ⇒ Boolean
(also: #==)
‘true` if the members of the other `TinyStruct` instance are equal to the values of this `TinyStruct` instance.
- #inspect ⇒ Object (also: #to_s)
Class Attribute Details
.cache ⇒ Object
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
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.
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 |
#inspect ⇒ Object 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 |