Class: Attribeauty::Base

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

Overview

base class to inherit from class MyClass < Attribeauty::Base

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**attributes) ⇒ Base

Returns a new instance of Base.



30
31
32
33
34
35
# File 'lib/attribeauty/base.rb', line 30

def initialize(**attributes)
  attributes.each do |key, value|
    method = "#{key}=".to_sym
    public_send(method, value)
  end
end

Class Method Details

.attribute(name, type, **args) ⇒ Object



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

def self.attribute(name, type, **args)
  @attributes ||= {}
  return if @attributes[name]

  @attributes[name] = type

  class_eval(<<-CODE, __FILE__, __LINE__ + 1)
    def #{name}=(value)
      validator = Validator.run(#{name.inspect}, value, #{type.inspect}, #{args})
      raise MissingAttributeError, validator.errors.join(', ') if validator.errors.any?
      @#{name} = validator.value
    end

    def #{name};@#{name};end
  CODE

  return unless type == :boolean

  class_eval(<<-CODE, __FILE__, __LINE__ + 1)
    def #{name}?; !!#{name}; end
  CODE
end

Instance Method Details

#assign_attributes(**attributes) ⇒ Object



37
38
39
40
41
42
# File 'lib/attribeauty/base.rb', line 37

def assign_attributes(**attributes)
  attributes.each do |key, value|
    method = "#{key}=".to_sym
    public_send(method, value)
  end
end