Module: AlphaCard::Attribute::ClassMethods

Defined in:
lib/alpha_card/attribute.rb

Overview

Attributes class methods

* attribute
* remove_attribute
* attributes_set

Instance Method Summary collapse

Instance Method Details

#attribute(name, options = {}) ⇒ Object

Adds attribute to the class. Defines reader and writer methods based on options hash. Adds attribute to the global Attributes Set.

Examples:

class User
  include AlphaCard::Attribute

  attribute :id, type: Integer, required: true, writable: false
  attribute :email, required: true, format: /.+@.+/
  attribute :name, type: String
  attribute :role, default: 'admin', values: ['admin', 'regular']
  attribute :status, types: [String, Symbol]

  attribute :metadata, type: Hash
  attribute :additional_info
end

Parameters:

  • name (Symbol, String)

    attribute name

  • options (Hash) (defaults to: {})

    attribute options



54
55
56
57
58
59
# File 'lib/alpha_card/attribute.rb', line 54

def attribute(name, options = {})
  define_reader(name)
  define_writer(name, options) if options[:writable].nil? || options[:writable]

  attributes_set[name.to_sym] = options
end

#attributes_setHash

Defines Attributes Set for the class. Attributes set contains all the attributes names as key and it’s options as the value.

Returns:

  • (Hash)

    attributes set with options



29
30
31
# File 'lib/alpha_card/attribute.rb', line 29

def attributes_set
  @attributes_set ||= {}
end

#remove_attribute(name) ⇒ Object

Removes attribute from the class (reader, writer and entry in Attributes Set).

Examples:

class User
  include AlphaCard::Attribute

  attribute :email
  attribute :name, default: 'John'
end

class Person < User
  attribute :email
  remove_attribute :name
end

Parameters:

  • name (String, Symbol)

    attribute name



78
79
80
81
82
83
84
85
86
87
# File 'lib/alpha_card/attribute.rb', line 78

def remove_attribute(name)
  symbolized_name = name.to_sym

  if attributes_set.keys.include?(symbolized_name)
    undef_method(symbolized_name)
    undef_method("#{name}=") if method_defined?("#{name}=")

    attributes_set.delete(symbolized_name)
  end
end