Module: AttributeHelpers

Defined in:
lib/attribute_helpers.rb,
lib/attribute_helpers/version.rb

Overview

Provides helper functionality for ruby classes that store various database-unfriendly types as instance variables. It automatically serializes and deserializes things like classes and symbols to interact easily with both the database and your application code.

Constant Summary collapse

VERSION =
"0.0.1"

Instance Method Summary collapse

Instance Method Details

#attr_class(*attrs) ⇒ Object

Marks attributes as storing class values, providing setters and getters for the attributes that will allow the application to use them as a classes but store them internally as strings.

Parameters:

  • attrs (*Symbol)

    a list of the names of attributes that store classes


36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/attribute_helpers.rb', line 36

def attr_class(*attrs)
  attrs.each do |attr|
    # Store the original methods for use in the overwritten ones.
    original_getter = instance_method(attr)
    original_setter = instance_method("#{attr}=")

    # Overwrite the accessor.
    define_method attr do
      val = original_getter.bind(self).call
      val && Kernel.const_get(val)
    end

    # Overwrite the mutator.
    define_method "#{attr}=" do |val|
      original_setter.bind(self).call(val && val.to_s)
    end
  end
end

#attr_symbol(*attrs) ⇒ Object

Marks attributes as storing symbol values, providing setters and getters for the attributes that will allow the application to use them as a symbols but store them internally as strings.

Parameters:

  • attrs (*Symbol)

    a list of the names of attributes that store symbols


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/attribute_helpers.rb', line 13

def attr_symbol(*attrs)
  attrs.each do |attr|
    # Store the original methods for use in the overwritten ones.
    original_getter = instance_method(attr)
    original_setter = instance_method("#{attr}=")

    # Overwrite the accessor.
    define_method attr do
      val = original_getter.bind(self).call
      val && val.to_sym
    end

    # Overwrite the mutator.
    define_method "#{attr}=" do |val|
      original_setter.bind(self).call(val && val.to_s)
    end
  end
end