Method: Jason::Persistence::ClassMethods#attribute

Defined in:
lib/jason/persistence.rb

#attribute(*args) ⇒ Object

PUBLIC Add attribute to persistence layer for this model.

Defines getter and setter methods for given attribute

The Setter methods converts the attribute into the given data type.

args - List of arguments:

* first argument   - attribute name as symbol
* second argument  - data type of attribute

Currently three data types are supported:

  • String

  • Integer

  • Date



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/jason/persistence.rb', line 87

def attribute(*args)
  attribute_name,attribute_type = args[0], args[1]

  unless DATA_TYPES.keys.include?("#{attribute_type}".to_sym)
    raise Errors::NotSupportedDataTypeError.new("This Kind of type is not supported or missing!") 
  end

  cast_to = DATA_TYPES["#{attribute_type}".to_sym]#eval "Jason::#{attribute_type}"

  define_method attribute_name do 
    instance_variable_get("@#{attribute_name}")
  end

  define_method "#{attribute_name}=" do |attribute|
    instance_variable_set("@#{attribute_name}", attribute.send(cast_to))
  end

  defined_attributes << {:name => attribute_name, :type => attribute_type} unless defined_attributes.include?(attribute_name)

  unless defined_attributes_include?(:id)
    define_method :id do 
      instance_variable_get("@id")
    end

    define_method "id=" do |val|
      instance_variable_set("@id", val)
    end
    defined_attributes << {:name => :id, :type => String}
  end
end