Module: Sanity::Attributable

Defined in:
lib/sanity/attributable.rb

Overview

Attributable is responsible for setting the appropriate attributes on an object in memory

The attribute marco is used to define the available attributes and the default return value if applicable

Examples:

provides getter and setter methods for ‘_id` and sets the default value to an empty string

attribute :_id, default: ""

Defined Under Namespace

Modules: ClassMethods

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



37
38
39
# File 'lib/sanity/attributable.rb', line 37

def attributes
  @attributes
end

Class Method Details

.included(base) ⇒ Object



15
16
17
# File 'lib/sanity/attributable.rb', line 15

def included(base)
  base.extend(ClassMethods)
end

Instance Method Details

#initialize(**args) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/sanity/attributable.rb', line 39

def initialize(**args)
  self.class.default_attributes.merge(args).then do |attrs|
    attrs.each do |key, val|
      define_singleton_method(:"#{key}=") do |val|
        args[key] = val
        attributes[key] = val
      end

      define_singleton_method(key) { args[key] }
    end

    instance_variable_set(:@attributes, attrs)
  end
end

#inspectObject



54
55
56
57
58
# File 'lib/sanity/attributable.rb', line 54

def inspect
  attributes.keys.map { |key| "#{key}: #{attributes[key].inspect}" }.join(", ").then do |attrs|
    attrs.empty? ? "#<#{_instance}>" : "#<#{_instance} #{attrs}>"
  end
end