Module: NinjaModel::AttributeMethods

Included in:
Base
Defined in:
lib/ninja_model/attribute_methods.rb

Defined Under Namespace

Classes: AttributeAssignmentError, MultiparameterAssignmentErrors

Instance Method Summary collapse

Instance Method Details

#[](attr_name) ⇒ Object



91
92
93
# File 'lib/ninja_model/attribute_methods.rb', line 91

def [](attr_name)
  read_attribute(attr_name)
end

#[]=(attr_name, value) ⇒ Object



95
96
97
# File 'lib/ninja_model/attribute_methods.rb', line 95

def []=(attr_name, value)
  write_attribute(attr_name, value)
end

#attribute_method?(name) ⇒ Boolean

Returns:

  • (Boolean)


116
117
118
119
# File 'lib/ninja_model/attribute_methods.rb', line 116

def attribute_method?(name)
  name = name.to_s
  self.class.model_attributes_hash.key?(name)
end

#attributes=(new_attributes) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/ninja_model/attribute_methods.rb', line 99

def attributes=(new_attributes)
  return unless new_attributes.is_a?(Hash)
  attributes = new_attributes.stringify_keys

  multi_parameter_attributes = []

  attributes.each do |k,v|
    if k.include?('(')
      multi_parameter_attributes << [k, v]
    else
      respond_to?("#{k}=".to_sym) ? send("#{k}=".to_sym, v) : raise(NinjaModel::Base::UnknownAttributeError, "unknown attribute: #{k}")
    end
  end

  assign_multiparameter_attributes(multi_parameter_attributes)
end

#attributes_from_model_attributesObject



66
67
68
69
70
71
# File 'lib/ninja_model/attribute_methods.rb', line 66

def attributes_from_model_attributes
  self.class.model_attributes.inject({}) do |result, attr|
    result[attr.name] = attr.default unless attr.name == self.class.primary_key
    result
  end
end

#read_attribute(name) ⇒ Object



82
83
84
85
86
87
88
89
# File 'lib/ninja_model/attribute_methods.rb', line 82

def read_attribute(name)
  name = name.to_s
  if !(value = @attributes[name]).nil?
    self.class.model_attributes_hash[name].convert(@attributes[name])
  else
    nil
  end
end

#write_attribute(name, value) ⇒ Object



73
74
75
76
77
78
79
80
# File 'lib/ninja_model/attribute_methods.rb', line 73

def write_attribute(name, value)
  name = name.to_s
  if a = self.class.model_attributes_hash[name]
    @attributes[name] = value
  else
    raise NoMethodError, "Unknown attribute #{name.inspect}"
  end
end