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


74
75
76
77
78
79
80
81
# File 'lib/shallow_attributes/class_methods.rb', line 74

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

  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


48
49
50
# File 'lib/shallow_attributes/class_methods.rb', line 48

def attributes
  default_values.keys
end

#default_valuesHash

Returns hash which contain default values for each attribute

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.

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