Module: FinerStruct

Defined in:
lib/finer_struct/mutable.rb,
lib/finer_struct/version.rb,
lib/finer_struct/immutable.rb

Defined Under Namespace

Classes: Immutable, Mutable

Constant Summary collapse

VERSION =
"0.0.1"

Class Method Summary collapse

Class Method Details

.Immutable(*attribute_names) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/finer_struct/immutable.rb', line 17

def self.Immutable(*attribute_names)
  Class.new do
    @attribute_names = attribute_names

    class << self
      attr_reader :attribute_names
    end

    attr_reader(*attribute_names)

    def initialize(attributes = {})
      attributes.each_pair do |key, value|
        unless self.class.attribute_names.include?(key)
          raise(ArgumentError, "no such attribute: #{key}")
        end
        instance_variable_set("@#{key}", value)
      end
    end
  end
end

.Mutable(*attribute_names) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/finer_struct/mutable.rb', line 25

def self.Mutable(*attribute_names)
  Class.new do
    @attribute_names = attribute_names

    class << self
      attr_reader :attribute_names
    end

    attr_accessor(*attribute_names)

    def initialize(attributes = {})
      attributes.each_pair do |key, value|
        unless self.class.attribute_names.include?(key)
          raise(ArgumentError, "no such attribute: #{key}")
        end
        instance_variable_set("@#{key}", value)
      end
    end
  end
end