Class: HashStruct

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

Class Method Summary collapse

Class Method Details

.generate(*attributes) ⇒ Object

User = HashStruct.generate(:first_name, :last_name)

Raises:

  • (ArgumentError)


6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/hash_struct.rb', line 6

def self.generate(*attributes)
  raise ArgumentError, "you have to specify some attributes" if attributes.empty?

  included = self.included_modules
  extended = (class << self; self; end).included_modules

  Class.new(self) do
    # setup accessors
    attributes.each do |attribute|
      attr_accessor attribute
    end

    # initialize
    def initialize(attributes = Hash.new)
      attributes.each do |attribute, value|
        self.send("#{attribute}=", value)
      end
    end
  end
end