Module: Mitake::Model::Accessor Private

Defined in:
lib/mitake/model/accessor.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Since:

  • 0.1.0

Instance Method Summary collapse

Instance Method Details

#attribute(name, type = 'String', readonly: false) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Define attribute

Parameters:

  • name (String|Symbol)

    the attribute name

  • type (Class) (defaults to: 'String')

    the attribute type

  • readonly (TrueClass|FalseClass) (defaults to: false)

    is attribute readonly

Since:

  • 0.1.0



36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/mitake/model/accessor.rb', line 36

def attribute(name, type = 'String', readonly: false)
  @attributes ||= {}
  @attributes[name.to_s] = type.to_s

  define_method name do
    instance_variable_get("@#{name}")
  end
  return if readonly

  define_method "#{name}=" do |value|
    instance_variable_set("@#{name}", self.class.cast(value, type.to_s))
  end
end

#attribute_namesArray

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Get attribute names

Returns:

  • (Array)

    the list of attribute names

Since:

  • 0.1.0



25
26
27
# File 'lib/mitake/model/accessor.rb', line 25

def attribute_names
  attributes.keys
end

#attributesHash

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Get attributes

Returns:

  • (Hash)

    the list of attributes and type

Since:

  • 0.1.0



16
17
18
# File 'lib/mitake/model/accessor.rb', line 16

def attributes
  @attributes ||= {}
end

#cast(value, type = 'String') ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Casting type

Parameters:

  • value (Object)

    the source value

  • type (Class) (defaults to: 'String')

    the cast type

Since:

  • 0.1.0



57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/mitake/model/accessor.rb', line 57

def cast(value, type = 'String')
  case type.to_s
  when 'String', 'Integer', 'Float'
    Kernel.method(type).call(value)
  when 'Time', 'DateTime', 'Date'
    Kernel.const_get(type).parse("#{value}+8")
  else
    klass = Kernel.const_get(type)
    return klass.parse(value) if klass.respond_to?(:parse)

    value
  end
end