Module: ShallowAttributes::ClassMethods Abstract

Defined in:
lib/shallow_attributes/class_methods.rb

Overview

This module is abstract.

Abstract class for value classes. Provides some helper methods for working with class methods.

Since:

  • 0.1.0

Instance Method Summary collapse

Instance Method Details

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

Define attribute with specific type and default value for current class.

Examples:

Create new User instance

class User
  include ShallowAttributes
  attribute :name, String, default: 'Anton'
end

User.new              # => #<User @attributes={:name=>"Anton"}, @name="Anton">
User.new(name: 'ben') # => #<User @attributes={:name=>"Ben"}, @name="Ben">

Parameters:

  • name (String, Symbol)

    the attribute name

  • type (String, Symbol)

    the type of attribute

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

    the attribute options

Options Hash (options):

  • :default (Object)

    default value for attribute

  • :of (Class)

    class of array elems

  • :allow_nil (boolean)

    cast ‘nil` to integer or float

  • :present (boolean)

    raise error if attribute was not provided

Returns:

  • (Object)

Since:

  • 0.1.0



86
87
88
89
90
91
92
93
94
# File 'lib/shallow_attributes/class_methods.rb', line 86

def attribute(name, type, options = {})
  options[:default] ||= [] if type == Array

  default_values[name] = options.delete(:default)
  mandatory_attributes[name] = options.delete(:present)

  initialize_setter(name, type, options)
  initialize_getter(name)
end

#attributesHash

Returns all class attributes.

Examples:

Create new User instance

class User
  include ShallowAttributes
  attribute :name, String
  attribute :last_name, String
  attribute :age, Integer
end

User.attributes # => [:name, :last_name, :age]

Returns:

  • (Hash)

Since:

  • 0.1.0



59
60
61
# File 'lib/shallow_attributes/class_methods.rb', line 59

def attributes
  default_values.keys
end

#default_valuesHash

Returns hash that contains default values for each attribute

Returns:

  • (Hash)

    hash with default values

Since:

  • 0.1.0



29
30
31
# File 'lib/shallow_attributes/class_methods.rb', line 29

def default_values
  @default_values ||= {}
end

#inherited(subclass) ⇒ Object

Inject our default values into subclasses.

Parameters:

  • subclass (Object)

Since:

  • 0.1.0



15
16
17
18
19
20
# File 'lib/shallow_attributes/class_methods.rb', line 15

def inherited(subclass)
  super
  if respond_to?(:default_values)
    subclass.default_values.merge!(default_values)
  end
end

#mandatory_attributesHash

Returns hash that contains mandatory attributes

Returns:

  • (Hash)

    hash with mandatory attributes

Since:

  • 0.10.0



40
41
42
# File 'lib/shallow_attributes/class_methods.rb', line 40

def mandatory_attributes
  @mandatory_attributes ||= {}
end