class TinyStruct
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.
Constants
- ATTRIBUTE_PATTERN
- VERSION
Attributes
cache[RW]
Public Class Methods
configure() { |self| ... }
click to toggle source
Yields `TinyStruct` to a block such that you can toggle configuration settings. For example:
TinyStruct.configure do |config| config.cache = false end
# File lib/tiny_struct.rb, line 63 def configure yield self end
new(*members)
click to toggle source
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.
# 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
Private Class Methods
class_cache()
click to toggle source
# File lib/tiny_struct.rb, line 95 def class_cache @class_cache ||= cache ? MemoryCache.new : ObjectSpaceCache.new end
define_class(members)
click to toggle source
# File lib/tiny_struct.rb, line 69 def define_class(members) clazz = Class.new(TinyStruct) do attr_reader(*members) define_singleton_method(:new, Object.method(:new)) define_singleton_method(:members) { members } end define_initialize_method(clazz, members) clazz end
define_initialize_method(clazz, members)
click to toggle source
# File lib/tiny_struct.rb, line 81 def define_initialize_method(clazz, members) clazz.send(:define_method, :initialize) do |*arguments| if members.size != arguments.size message = "wrong number of arguments (given #{arguments.size}, " \ "expected #{members.size})" raise ArgumentError, message end members.zip(arguments).each do |name, value| instance_variable_set(:"@#{name}", value) end end end
Public Instance Methods
eql?(other)
click to toggle source
`true` if the members of the other `TinyStruct` instance are equal to the values of this `TinyStruct` instance.
# 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
Also aliased as: ==
inspect()
click to toggle source
# 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
Also aliased as: to_s