Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/ys1/core_ext/hash.rb

Overview

OpenClass Hash

Instance Method Summary collapse

Instance Method Details

#to_anon_class ⇒ Class

Builds an anonymous class from the hash.

Each hash key becomes an attribute with both reader and writer methods. The corresponding values are assigned when an instance is initialized.

Examples:

hash = { name: "Alice", age: 30 }
klass = hash.to_anon_class
obj = klass.new
obj.name #=> "Alice"
obj.age  #=> 30

Returns:

  • (Class) —

    An anonymous class with accessor methods for each hash key, pre-populated with the hash’s values.



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/ys1/core_ext/hash.rb', line 22

def to_anon_class
  hash = self

  Class.new do
    hash.each_key { |key| attr_accessor key }

    define_method(:initialize) do
      hash.each { |key, value| instance_variable_set("@#{key}", value) }
    end
  end
end