module ModelX::Attributes::ClassMethods
Public Instance Methods
attribute(*attributes)
click to toggle source
@!method attribute(*attributes, options = {}) DSL method to define attributes.
@option options :default
A default value for the attribute.
@option options [Symbol] :type
A type for the attribute.
# 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
attributes()
click to toggle source
@!attribute [r] attributes @return [Array] An array of defined attribute names.
# File lib/model_x/attributes.rb, line 81 def attributes @attributes ||= [] end
Private Instance Methods
_model_x_convert(attribute, value)
click to toggle source
# File lib/model_x/attributes.rb, line 142 def _model_x_convert(attribute, value) if @_model_x_types[attribute] if ModelX.const_defined?(@_model_x_types[attribute].to_s.camelize) ModelX.const_get(@_model_x_types[attribute].to_s.camelize).convert(value) else raise "no converter found for type #{@_model_x_types[attribute]}" end else value end end
_model_x_default(attribute)
click to toggle source
# File lib/model_x/attributes.rb, line 134 def _model_x_default(attribute) if @_model_x_defaults && @_model_x_defaults.key?(attribute) @_model_x_defaults[attribute] elsif superclass.private_methods.include?(:_model_x_default) superclass.send :_model_x_default, attribute end end