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">

Options Hash (options):

  • :default (Object)

    default value for attribute

  • :of (Class)

    class of array elems

  • :allow_nil (boolean)

    cast `nil` to integer or float

Since:

  • 0.1.0


66
67
68
69
70
71
72
73
74
# File 'lib/shallow_attributes/class_methods.rb', line 66

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

  @default_values ||= {}
  @default_values[name] = options.delete(:default)

  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]

Since:

  • 0.1.0


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

def attributes
  default_values.keys
end

#default_valuesHash

Returns hash which contain default values for each attribute

Since:

  • 0.1.0


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

def default_values
  if superclass.respond_to?(:default_values)
    @default_values.merge!(superclass.default_values) { |_, v, _| v }
  else
    @default_values
  end
end