Module: ModelX::Attributes::ClassMethods

Defined in:
lib/model_x/attributes.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#attributesArray (readonly)



81
82
83
# File 'lib/model_x/attributes.rb', line 81

def attributes
  @attributes ||= []
end

Instance Method Details

#attribute(*attributes, options = {}) ⇒ Object

DSL method to define attributes.

Options Hash (options):

  • :default (Object)

    A default value for the attribute.

  • :type (Symbol)

    A type for the attribute.



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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/model_x/attributes.rb', line 92

def attribute(*attributes)
  options = attributes.extract_options!

  @_model_x_defaults ||= {}
  @_model_x_types ||= {}

  attributes.each do |attribute|
    attribute = attribute.to_sym

    if instance_methods.include?(attribute)
      raise AttributeAlreadyDefined, "attribute :#{attribute} is already defined on #{self.name}"
    end
    self.attributes << attribute

    @_model_x_defaults[attribute] = options[:default] if options.key?(:default)
    @_model_x_types[attribute] = options[:type]

    class_eval <<-RUBY, __FILE__, __LINE__+1

      def #{attribute}
        value = read_attribute(:#{attribute})
        value = self.class.send(:_model_x_default, :#{attribute}) if value.nil?
        value
      end

      def #{attribute}=(value)
        write_attribute :#{attribute}, value
      end

    RUBY

    if options[:type]
      class_eval <<-RUBY, __FILE__, __LINE__+1
        #{options[:type]} :#{attribute}
      RUBY
    end

  end
end