Class: Hash

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

Overview

OpenClass Hash

Instance Method Summary collapse

Instance Method Details

#to_anon_classClass

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
33
34
# File 'lib/ys1/hash_to_class.rb', line 22

def to_anon_class
  source = self

  Class.new do
    source.each_key { |key| attr_accessor key.to_sym }

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